如何用Python或命令行获取Windows文件夹安全属性
获取Windows文件夹的用户和组权限列表(Python实现)
要实现你说的手动查看文件夹Security选项卡的功能,用Python可以借助PowerShell的原生命令来完成——毕竟Python标准库没有直接操作Windows ACL(访问控制列表)的模块,而PowerShell能轻松调用系统的权限查询接口,而且不需要安装任何额外包。
核心思路
通过Python的subprocess模块调用PowerShell的Get-Acl命令,获取文件夹的访问控制列表,然后解析返回的结果,提取用户/组名称、权限等关键信息。
完整代码示例
import subprocess import json def get_folder_security_info(folder_path): # 构造PowerShell命令:获取文件夹ACL,展开Access属性并转为JSON格式 ps_command = f''' Get-Acl -Path "{folder_path}" | Select-Object -ExpandProperty Access | ConvertTo-Json -Depth 10 ''' try: # 执行PowerShell命令,捕获输出 result = subprocess.run( ["powershell", "-Command", ps_command], capture_output=True, text=True, check=True ) # 解析JSON输出 access_entries = json.loads(result.stdout) # 整理需要的信息:用户/组、权限类型、具体权限 security_info = [] for entry in access_entries: security_info.append({ "user_or_group": entry["IdentityReference"]["Value"], "access_type": entry["AccessControlType"], "rights": entry["FileSystemRights"] }) return security_info except subprocess.CalledProcessError as e: return f"命令执行出错: {e.stderr}" except json.JSONDecodeError: return "解析权限信息失败" # 用法示例 if __name__ == "__main__": target_folder = r"C:\Users\YourName\Documents" # 替换成你的目标文件夹路径 info = get_folder_security_info(target_folder) if isinstance(info, list): print("文件夹的用户/组权限列表:") for item in info: print(f"- 用户/组: {item['user_or_group']}") print(f" 访问类型: {item['access_type']}") print(f" 权限: {item['rights']}\n") else: print(info)
代码说明
PowerShell命令解析:
Get-Acl -Path "{folder_path}":获取目标文件夹的访问控制列表Select-Object -ExpandProperty Access:展开Access属性,这个属性里包含了所有用户/组的权限条目ConvertTo-Json -Depth 10:把结果转为JSON格式,方便Python解析(设置Depth是因为默认深度不够会截断嵌套结构)
Python部分解析:
- 使用
subprocess.run执行PowerShell命令,capture_output=True捕获命令的输出和错误,text=True让输出以字符串形式返回 - 用
json.loads解析JSON结果,然后提取关键字段:IdentityReference.Value是用户/组的名称,AccessControlType是允许或拒绝,FileSystemRights是具体的权限(比如读取、写入等)
- 使用
错误处理:
- 捕获
subprocess.CalledProcessError处理命令执行失败的情况(比如文件夹不存在、没有权限) - 捕获
json.JSONDecodeError处理解析JSON失败的情况
- 捕获
这个方法得到的结果和你手动打开Properties->Security看到的用户/组列表以及权限完全一致,而且只用了Python标准库,不需要额外安装任何包。
内容的提问来源于stack exchange,提问作者vy32




