如何在Windows上移除文件权限?

0 投票
1 回答
1867 浏览
提问于 2025-04-18 01:12

我使用了以下的答案来给一个文件授权访问,感谢@kindall的分享。你可以在这里查看这个答案:https://stackoverflow.com/a/12168268/740899

> import win32security 
> import ntsecuritycon as con
> 
> FILENAME = "whatever"
> 
> userx, domain, type = win32security.LookupAccountName ("", "User X")
> 
> sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION) 
> dacl = sd.GetSecurityDescriptorDacl()   # instead of dacl = win32security.ACL()
> 
> dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, userx)
> 
> sd.SetSecurityDescriptorDacl(1, dacl, 0)   # may not be necessary
> win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

不过,我需要的访问权限是临时的。所以我用 dacl.AddAccessDeniedAce 替代了上面提到的 dacl.AddAccessAllowedAce。但是这样做有个问题,因为我的用户将来还需要临时访问权限。在运行了 AddAccessDeniedAce 之后,如果再运行 AddAccessAllowedAce,被拒绝的控制依然存在,用户还是无法访问这个文件。当用户不再需要访问权限时,我希望能完全移除他们的访问权限。这可以通过Windows资源管理器的属性菜单来完成:

enter image description here

我一直找不到相关的文档来支持这个操作。有没有人知道如何通过操作dacl来做到这一点?还是说我必须通过Windows界面手动来完成?

1 个回答

0

在这里找到了解决办法: http://voices.canonical.com/tag/windows/

我稍微调整了一下,但现在可以用了。呼,终于搞定了!

def remove_ace(path,usernames):
    """Remove the ace for the given users."""
    if not os.path.exists(path):
        raise WindowsError('Path %s could not be found.' % path)
    total = 0
    for x in usernames:
        userx, domain, utype = win32security.LookupAccountName("", x)
        sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()
        num_delete = 0
        for index in range(0, dacl.GetAceCount()):
            ace = dacl.GetAce(index - num_delete)
            if userx == ace[2]:
                dacl.DeleteAce(index - num_delete)
                num_delete += 1
                total += 1
        if num_delete > 0:
            sd.SetSecurityDescriptorDacl(1, dacl, 0)
            win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
    if total > 0:
        return True

撰写回答