faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 9 people (56%) answered Yes
Recently 4 of 8 people (50%) answered Yes

Entry

Setting user priviliges (was: Running a program as another user on Win32)

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 277, Mark Hammond


"""
Packages: operating_systems.windows
"""
"""
>I am writing a bunch of scripts that will need to run as Administrator
>(Domain Administrator) on Windows NT 4.0 workstation clients that
>belong to an NT domain. I've tried using LogonUser, but I always get
>the following: pywintypes.api_error: (1314, 'LogonUser', ' A required
>privilege is not held by the client.'). I've also tried using LogonUser
>with the local Administrator account on my NT machine with no luck.
You need to explicitely enable the privilege.  The following function should
do the job.  The documentation on CreateProcessAsUser is vague, and I dont
have time to test it.  It appears you need some or all of the following
privileges (all from the ntsecuritycon module):
SE_ASSIGNPRIMARYTOKEN_NAME,
SE_INCREASE_QUOTA_NAME TOKEN_DUPLICATE, TOKEN_IMPERSONATE
"""
def AdjustPrivilege(priv, enable = 1):
    # Get the process token.
    flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
    # Get the ID for the privilege.
    id = win32security.LookupPrivilegeValue(None, priv)
    # Now obtain the privilege for this process.
    # Create a list of the privileges to be added.
    if enable:
        newPrivileges = [(id, SE_PRIVILEGE_ENABLED)]
    else:
        newPrivileges = [(id, 0)]
    # and make the adjustment.
    win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)