[python-win32] Reg. taking folder ownership

Goku Balu tfa.signup.test1 at gmail.com
Mon Aug 27 07:23:50 EDT 2018


Hi,
My use case is this. Folder1 is created by Admin1 and ACL is set by Admin1.
Now Admin2 wants to change the ACL. I think we have two options here
1) Take folder ownership and the do the changes
2) Take elevated privileges for Admin2 account and add/remove ACL entries
(Similar to "Run as Administrator" and using icalcs in cmd)

I'm trying to solve this with the first approach. After Googling around,
here is the code I'm trying to run for taking ownership from Admin1 and
assign it to Admin2.

import win32api
import win32con
import win32security
import ntsecuritycon

def take_owner(path,account_name):
    #print("sid=",sid)
    owner_sid = win32security.LookupAccountName(None, account_name)[0]
    new_privs = (
        (win32security.LookupPrivilegeValue(
            '', ntsecuritycon.SE_RESTORE_NAME),
         win32con.SE_PRIVILEGE_ENABLED),
        (win32security.LookupPrivilegeValue(
            '', ntsecuritycon.SE_TAKE_OWNERSHIP_NAME),
         win32con.SE_PRIVILEGE_ENABLED))

    flags = win32security.TOKEN_ALL_ACCESS\
            | win32con.TOKEN_ADJUST_PRIVILEGES\
            | win32con.TOKEN_IMPERSONATE

    try:
        thread = win32api.GetCurrentThread()
        handle = win32security.OpenThreadToken(
            thread, flags, False)
    except win32security.error as e:
        if e.errno == 1008:
            handle =
win32security.OpenProcessToken(win32api.GetCurrentProcess (), flags)

    win32security.AdjustTokenPrivileges(handle, 0, new_privs)

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

    win32security.SetFileSecurity(
        path, win32security.OWNER_SECURITY_INFORMATION, fs)

FILENAME = "D:\\Test"

account_name=win32api.GetUserNameEx (win32con.NameSamCompatible)
sd = win32security.GetFileSecurity (FILENAME,
win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)
file_owner = domain+"\\"+name

if account_name != file_owner:
    print("Account name and file owner is different")
    take_owner(FILENAME,account_name)
else:
    print("Account name and file owner is Same")

I'm getting (5, Access Denied) in SetFileSecurity. Am I missing something?
Also I would like to know is this the right way of doing things? Thanks

- Goku
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-win32/attachments/20180827/9501107f/attachment.html>


More information about the python-win32 mailing list