Question

I have used the following answer to grant access to a file. Courtesy of @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)

However, access needs to be temporary. So I used dacl.AddAccessDeniedAcein place of dacl.AddAccessAllowedAce shown above. However, this has undesirable behavior because my users will need temporary access again in the future. After running AddAccessDeniedAce and then rerunning AddAccessAllowedAce, the denied control remains in place, and my users still do not have access to the file. When the user no longer needs access, I'd like to remove them from access entirely. This can be done via properties menu in windows explorer:

enter image description here

I have not been able to find documentation to support such a task. Does anyone know how to do this by manipulating the dacl? Or will I have to do this manually via windows interface?

Was it helpful?

Solution

Found a solution here: http://voices.canonical.com/tag/windows/

I had to tweak it a bit, but it's working. Whew!

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top