如何在 windows 中使用 python 创建用户进程?

How in windows create process as user using python?

我尝试创建 python 脚本以作为用户启动进程(将来此代码将由 windows 服务从会话 0 运行 开始)。为此,我决定使用 win32api。

但是我有一个错误:

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.')

什么特权?如果我正确理解 this

,我想我已经获得了所有特权

我的代码:

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)

非常感谢任何帮助。

首先,这里是 msdn 上的示例 Starting an Interactive Client Process

其次,作为@RbMm 的指针:

您需要使用 CreateProcessWithLogonW 而不是 LogonUser + CreateProcessAsUser

根据文档:

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

This 似乎是在 Python.

中使用的示例

其他有用的文章:

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