[python-win32] Setting ownership and permissions

Joseph L. Casale jcasale at activenetwerx.com
Wed Dec 18 01:55:54 CET 2013


I have a situation where I need to remove large directories and in doing so I must take ownership.
I get a stack trace about the logon I impersonate generating to many security ids as I recursively
iterate and take ownership.

What workarounds have you guys utilized in this scenario?

I suspect there is room for optimizing the approach I am using, where I pass the sid of the new
owner in to this function that leverages the unc path in self.unc:

    def owner_set(self, owner_sid):
        new_privs = (
            (win32security.LookupPrivilegeValue(
                '', ntsecuritycon.SE_RESTORE_NAME),
             win32con.SE_PRIVILEGE_ENABLED),
            (win32security.LookupPrivilegeValue(
                '', ntsecuritycon.SE_TAKE_OWNERSHIP_NAME),
             win32con.SE_PRIVILEGE_ENABLED))

        thread = win32api.GetCurrentThread()
        handle = win32security.OpenThreadToken(
            thread, win32security.TOKEN_ALL_ACCESS
            | win32con.TOKEN_ADJUST_PRIVILEGES
            | win32con.TOKEN_IMPERSONATE, False)
        win32security.AdjustTokenPrivileges(handle, 0, new_privs)

        fs = win32security.GetFileSecurity(
            self.unc, win32security.OWNER_SECURITY_INFORMATION)
        fs.SetSecurityDescriptorOwner(owner_sid, True)

        win32security.SetFileSecurity(
            self.unc, win32security.OWNER_SECURITY_INFORMATION, fs)

Thanks,
jlc


More information about the python-win32 mailing list