【发布时间】:2016-05-20 09:48:18
【问题描述】:
我们需要检查当前的 Windows 帐户是否有 listdir/[List Folder Contents][1] 对 windows 文件夹的权限。目前我们正在使用os.access(path, os.R_OK)。但是,据我了解,Windows 用户可以在没有List folder Conents 权限的情况下读取文件夹。
我的测试:
创建一个文件夹,配置Security,拒绝List folder / read data权限。
当我在 Windows 文件资源管理器中访问它时,You don't currently have permission to access this folder - 这就是我所期待的。但是,当我在 python 中测试时:
>>> p = r'c:\tmp\p'
>>> os.stat(p)
nt.stat_result(st_mode=16895, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=0L, st_a
time=1463736204L, st_mtime=1463736204L, st_ctime=1463736135L)
>>> os.access(p, os.R_OK)
True
>>> os.listdir(p)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 5] Access is denied: 'c:\\tmp\\p/*.*'
os.access => 真; os.list => 异常
问题
我不认为os.access() 是测试List Folder Conents 权限的合适函数,Python 中是否有任何其他函数/lib 可以检查 listdir(List Folder Contents) 权限?
了解It's easier to ask for forgiveness than for permission,但我仍然想找到一种正确的方法来验证listdir 权限。谢谢!
【问题讨论】:
-
建议尝试操作并处理任何异常。因此,并没有迫切需要在 Windows 上增强
os.access以执行正确的 WinAPIAccessCheck。照原样,os.access仅检查只读文件属性,这对您没有用处。如果实施了适当的检查,那么测试os.R_OK将是正确的。列出文件夹的权限与读取数据的权限相同。 -
您可以使用子进程运行accesschk.exe 来检查当前用户的访问权限。例如:
user = os.environ['USERNAME'];out = subprocess.check_output('accesschk -qdv "%s" "%s"' % (user, path));list_access = any(x in out for x in [b'FILE_ALL_ACCESS', b'FILE_LIST_DIRECTORY'])。
标签: python windows permissions