作者sbrhsieh (sbr)
看板Python
标题Re: [问题] 再请教一个关於python做类似runas功能ꨠ…
时间Wed Feb 25 19:46:06 2009
※ 引述《deckloveyou (1985)》之铭言:
: 我装了win32套件後 想试着在python下更换使用者呼叫程式
: [略]
: 第一次印出来的使用者即是我当前登入的使用者 cHRIs
: 第二次印出来的使用者即是我欲改登入的使用者 test
: putty.exe也顺利的call出来了
: 可是我开工作管理员 发现putty.exe程序的使用者名称还是 cHRIs
: 咕狗了半天 似乎是windows XP环境需要做设定 但是怎麽试也试不出来
: 请各位前辈指点一条明路吧!!!
: 使用python 2.5 os是 windows XP
我还不知道为什麽你这样子的作法行不通,但我有试了其他几种作法企图达到
runas 的功能:CreateProcessAsUser, ShellExecuteEx, CreateProcessWithLogonW。
一开始我依照你的作法以 LogonUser 来登入使用者,取得 token 後再透过
CreateProcessAsUser/ShellExecuteEx 以该身份来启动指定的程式,结果跟你的
作法一样行不通,也试过先 impersonate 成该 user,一样也行不通。
後来发现 CreateProcessWithLogonW 可以把 logon 与 CreateProcessAsUser 一次
做完,试过之後的确可以做到在 shell 中以 runas 功用去执行程式的相同效果。
(使用这个作法在事件检视簿里的安全性一页中,登录的事件过程会与你按滑鼠右键
选 run as 来执行程式同)
看起来 pywin32 似乎还没有 wrap CreateProcessWithLogonW 这个 API,所以我透过
ctypes 套件来做(Python 2.5 开始有内建 ctypes):
# myshellutil.py
from ctypes import wintypes
from ctypes import *
class STARTUP_INFO(Structure):
_fields_ = [
('cb', wintypes.DWORD),
('lpReserved', c_wchar_p),
('lpDesktop', c_wchar_p),
('lpTitle', c_wchar_p),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', c_void_p),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE),
]
class PROCESS_INFO(Structure):
_fields_ = [
('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD),
]
CreateProcessWithLogon = windll.advapi32.CreateProcessWithLogonW
CreateProcessWithLogon.restype = wintypes.BOOL
CreateProcessWithLogon.argtypes = c_wchar_p, c_wchar_p, c_wchar_p, wintypes.DWORD, c_wchar_p, c_wchar_p, wintypes.DWORD, c_void_p, c_wchar_p, POINTER(STARTUP_INFO), POINTER(PROCESS_INFO)
CREATE_NEW_CONSOLE = 0x00000010
def runas(program_path, username, password, domain=None):
startup_info = STARTUP_INFO()
startup_info.cb = sizeof(startup_info)
proc_info = PROCESS_INFO()
if CreateProcessWithLogon(username, domain, password, 0, program_path, None, CREATE_NEW_CONSOLE, None, None, byref(startup_info), byref(proc_info)):
return proc_info.hProcess, proc_info.hThread, proc_info.dwProcessId, proc_info.dwThreadId
raise WinError()
===========================================================================
Usage:
import myshellutil
hProc, hThread, procId, threadId = myshellutil.runas(r'c:\python25\putty.exe', 'test', '1234', 'bedrock')
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.173.142.110
※ 编辑: sbrhsieh 来自: 218.173.142.110 (02/25 19:47)
※ 编辑: sbrhsieh 来自: 218.173.142.110 (02/25 19:50)
※ 编辑: sbrhsieh 来自: 218.173.142.110 (02/25 20:08)
1F:推 deckloveyou:感谢 明天早上来试试看 02/25 23:51