Re: [問題] 再請教一個關於python做類似runas功能ꨠ…

看板Python作者 (sbr)時間16年前 (2009/02/25 19:46), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/1
※ 引述《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)

02/25 23:51, , 1F
感謝 明天早上來試試看
02/25 23:51, 1F
文章代碼(AID): #19fI-1D_ (Python)
文章代碼(AID): #19fI-1D_ (Python)