ren ren - 1 year ago 201
Python Question

Setting folder permissions in Windows using Python

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 Source

You want the win32security module, which is a part of pywin32. Here's an example of doing the sort of thing you want to do.

That 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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download