Search code examples
pythonwinapicreateprocessasuser

How in windows create process as user using python?


I try to create python script to start process as user (In future this code will be run from session 0 by windows service). For this i decide to use win32api.

But I have an error:

win32process.CreateProcessAsUser(token, None, "c:\\windows\\notepad.exe", None, None, 0, 0, None, None, startup)
pywintypes.error: (1314, 'CreateProcessAsUser', 'A required privilege is not held by the client.')

What privilege? I think I'm already gave all privileges, if I correctly understand this

My code:

import win32con
import win32process
import win32security
import win32api


def adjust_privilege(privilege, enable=1):
    flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
    htoken = win32security.OpenProcessToken(
        win32api.GetCurrentProcess(), flags)
    id = win32security.LookupPrivilegeValue(None, privilege)
    if enable:
        new_privilege = [(id, win32security.SE_PRIVILEGE_ENABLED)]
    else:
        new_privilege = [(id, 0)]
    win32security.AdjustTokenPrivileges(htoken, 0, new_privilege)


if __name__ == "__main__":
    adjust_privilege(win32security.SE_TCB_NAME)
    adjust_privilege(win32security.SE_ASSIGNPRIMARYTOKEN_NAME)
    adjust_privilege(win32security.SE_INCREASE_QUOTA_NAME)

    user = "username"
    password = "password"
    domain = "domain"
    logontype = win32con.LOGON32_LOGON_INTERACTIVE
    provider = win32con.LOGON32_PROVIDER_WINNT50
    token = win32security.LogonUser(user, domain, password, logontype, provider)
    startup = win32process.STARTUPINFO()
    startup.dwFlags = win32process.STARTF_USESHOWWINDOW
    startup.wShowWindow = win32con.SW_SHOW
    startup.lpDesktop = 'winsta0\default'
    win32process.CreateProcessAsUser(token, None, "c:\\windows\\notepad.exe", None, None, 0, 0, None, None, startup)

I would really appreciate any help.


Solution

  • First, here is an example on msdn to Starting an Interactive Client Process.

    Second, As @RbMm pointer out:

    you need use CreateProcessWithLogonW instead LogonUser + CreateProcessAsUser

    According to the document:

    If this function fails with ERROR_PRIVILEGE_NOT_HELD (1314), use the CreateProcessWithLogonW function instead.

    This seems to be an example used in Python.

    Other useful articles:

    Launching an interactive process from Windows Service in Windows Vista and later