Setting folder permissions in Windows using Python
Question: I'm using Python to create a new personal folder when a users AD account is
created. The folder is being created but the permissions are not correct. Can
Python add the user to the newly created folder and change their permissions?
I'm not sure where to begin coding this.


Answer: You want the `win32security` module, which is a part of
[pywin32](http://sourceforge.net/projects/pywin32/). Here's [an
example](http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-
file.html) of doing the sort of thing you want to do.

The example creates a new DACL for the file and replaces the old one, but it's
easy to modify the existing one; all you need to do is get the existing DACL
from the security descriptor instead of creating an empty one, like so:

    
    
    import win32security
    import ntsecuritycon as con
    
    FILENAME = "whatever"
    
    userx, domain, type = win32security.LookupAccountName ("", "User X")
    usery, domain, type = win32security.LookupAccountName ("", "User Y")
    
    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)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, usery)
    
    sd.SetSecurityDescriptorDacl(1, dacl, 0)   # may not be necessary
    win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)
    

