permission change of files in python

前端 未结 3 605
陌清茗
陌清茗 2021-02-13 10:35

I want to change the file permission for all the files from my current directory tree. I am trying to open each directory and open the files and change the permission using

相关标签:
3条回答
  • 2021-02-13 11:23

    You can instead use an OS specific function call as follows:

    os.system('chmod 777 -R *')
    
    0 讨论(0)
  • 2021-02-13 11:37

    You are using os.walk incorrectly.

    for dirpath, dirnames, filenames in os.walk('.'):
        for filename in filenames:
            path = os.path.join(dirpath, filename)
            os.chmod(path, 0o777) # for example
    
    0 讨论(0)
  • 2021-02-13 11:41

    If you just want to make the file open to everyone, you can use the following class:

    import win32security
    import ntsecuritycon
    
    class Win32FileSecurityMod:
      def __init__(self):
        self.security_dict = {}
        # return tuple from LookupAccountName() is user, domain, type
        self.security_dict["Everyone"] = win32security.LookupAccountName("", "Everyone")
        self.security_dict["Administrators"] = win32security.LookupAccountName("", "Administrators")
        self.security_dict["CurrentUser"] = win32security.LookupAccountName("", win32api.GetUserName())
        self.admins = self.security_dict["Administrators"][0]
        self.everyone = self.security_dict["Everyone"][0]
        self.user = self.security_dict["CurrentUser"][0]
    
      def SetPromiscuousFileAccess(self, file_path):
        print(file_path)
        con = ntsecuritycon
        sd = win32security.GetFileSecurity(file_path,win32security.DACL_SECURITY_INFORMATION)
        dacl = win32security.ACL()
        # con.FILE_GENERIC_READ
        # con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE,
        # con.FILE_ALL_ACCESS
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.everyone)
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.user)
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.admins)
        # Put our new DACL into the Security Descriptor,
        # update the file with the updated SD, and use
        # CACLS to show what's what.
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION, sd)
    
      # Gets the attributes of the file by executing a shell command. Useful for testing
      # but it will have performance problems for large file sets.
      def GetCacls(self, file_path):
        out = []
        for line in os.popen("cacls %s" % file_path).read().splitlines():
          out.append(line)
        return out
    
    0 讨论(0)
提交回复
热议问题