0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
ionalchemist
  • 398
  • 2
  • 17
  • I am currently looking at [this post](http://stackoverflow.com/a/18742636/740899) to see if I can do it that way. – ionalchemist Apr 03 '14 at 16:19
  • So I have worked out that each of those methods add separate ACEs to the file. I believe I may need to delete the ACE. Working on that. – ionalchemist Apr 03 '14 at 18:11

1 Answers1

0

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
ionalchemist
  • 398
  • 2
  • 17