Chmod issue to change file permission using python

旧城冷巷雨未停 提交于 2019-12-03 17:00:13
Chaos

I found a solution here :)

Setting folder permissions in Windows using Python

import win32security
import ntsecuritycon as con
import os
import pdb
userx, domain, type = win32security.LookupAccountName ("", "Everyone")
directory='M:\intra\EU'
for dirpath, dirnames, filenames in os.walk('M:\intra\EU'):
    for FILENAME in filenames:
        sd = win32security.GetFileSecurity(directory+'\\'+FILENAME, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()   # instead of dacl = win32security.ACL()
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, userx)
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(directory+'\\'+FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

According to the NOTE of the os.chmod documentation:

Although Windows supports chmod(), you can only set the file's read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

The recommended solution didn't work on Python3 (modules not available). I took a different approach, to use the Windows command line.

In my case, I needed the "LOCAL SERVICE" account to have permission. I did:

    import subprocess
    args = ["icacls", directory,
            "/grant:r", 'LOCAL SERVICE:(OI)(CI)MF']
    subprocess.check_call(args)

Note that this permission seems to only work when set on a directory. For security reasons, it would also be a good idea to ensure that "directory" actually exists.

Also note that "LOCAL SERVICE" might go by a translated name. In German locale, for example, it is "Lokaler Dienst."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!