Python啓動外部exe方式

import win32security
import win32process
import win32api
import win32con
import win32event
import os
import subprocess
import shutil

'''
Python創建新進程的幾種方式
1.父進程阻塞,且可以控制子進程,推薦用subprocess模塊,替換了老的的os.system;os.spawn等,且可以傳遞startinfo等信息給子進程
2.父進程銷燬,用子進程替換父進程,用os.exe**,如os.execv,os.exel等系列。注意在調用此函數之後,子進程即刻取得父進程的id,原進程之後的函數皆無法運行,且原父進程的資源,如文件等的所有人也變成了新的子進程。如有特殊必要,可在調用此函數前釋放資源
3.異步啓動新進程,父進程在子進程啓動後,不阻塞,繼續走自己的路。Windows下可用win32api.WinExec及win32api.ShellExec。win32api.WinExec不會有console窗口,不過如果啓動的是bat文件,依然會生成console窗口
4.異步啓動新進程,父進程在子進程啓動後,不阻塞,繼續走自己的路。在windows下,同3,可以用win32process.CreateProcess() 和 CreateProcessAsUser(),參數也通同系統API下的CreateProcess,比3好的一點是可以穿很多控制參數及信息,比如使得新啓動bat文件也隱藏窗口等
5.用阻塞的方式創建一個新進程,如os.system,subprocess等,然後通過設置進程ID或銷燬父進程的方法把新的子進程變成一個daemon進程,此方法應該用在linux系統環境中,未測試
'''

'''
CreateProcess(appName, commandLine , processAttributes ,
threadAttributes , bInheritHandles ,
dwCreationFlags , newEnvironment , currentDirectory , startupinfo

其參數含義如下。
appName:可執行的文件名。
commandLine:命令行參數。
processAttributes:進程安全屬性,如果爲None,則爲默認的安全屬性。
threadAttributes:線程安全屬性,如果爲None,則爲默認的安全屬性。
bInheritHandles:繼承標誌。
dwCreationFlags:創建標誌。
newEnvironment:創建進程的環境變量。
currentDirectory:進程的當前目錄。
startupinfo :創建進程的屬性。
'''
def OpenProcess0(procPath, param = ""):
    commandline = "\"" + procPath + "\" " + param
    handle = win32process.CreateProcess(None,
	       commandline, None, None, 0,
	       win32process.CREATE_NO_WINDOW, 
	        None , 
	        None,
	        win32process.STARTUPINFO())
    rc = win32event.WaitForSingleObject(handle[0], 10000)
    print rc
    
'''
win32process.CreateProcessAsUser

PyHANDLE, PyHANDLE, int, int = CreateProcessAsUser(hToken, appName , commandLine , processAttributes , 
threadAttributes , bInheritHandles , dwCreationFlags , newEnvironment , currentDirectory , startupinfo )
Creates a new process in the context of the specified user.

Parameters
hToken : PyHANDLE
    Handle to a token that represents a logged-on user

appName : string
    name of executable module, or None

commandLine : string
    command line string, or None

processAttributes : PySECURITY_ATTRIBUTES
    process security attributes, or None

threadAttributes : PySECURITY_ATTRIBUTES
    thread security attributes, or None

bInheritHandles : int
    handle inheritance flag

dwCreationFlags : int
    creation flags

newEnvironment : None
    A dictionary of stringor Unicode pairs to define the environment for the process, or None to inherit the current environment.

currentDirectory : string
    current directory name, or None
    
startupinfo : PySTARTUPINFO
    a STARTUPINFO object that specifies how the main window for the new process should appear.
'''
def OpenProcess1(procPath, param = "", securityLevel = ""):
    try:
	# 獲取用戶句柄
	hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_DUPLICATE | win32con.TOKEN_ADJUST_DEFAULT\
	                                        |win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY)
	hNewToken = hToken
	if securityLevel != "":
	    authority = 0x0002000
	    if securityLevel.lower() == "low":
		authority = 0x0001000
	    hNewToken = win32security.DuplicateTokenEx(hToken, win32security.SecurityImpersonation, 0, win32security.TokenPrimary, None)
	    # 構建相應級別的sid
	    sid = win32security.SID()
	    sid.Initialize((0, 0, 0, 0, 0, 16), 1)
	    sid.SetSubAuthority(0, authority)
	
	    # 將sid設置到用戶句柄
	    win32security.SetTokenInformation(hNewToken, win32security.TokenIntegrityLevel,(sid, win32security.SE_GROUP_INTEGRITY))
	    
	commandline = "\"" + procPath + "\" " + param
	# 啓動程序
	si = win32process.STARTUPINFO()
	win32process.CreateProcessAsUser(None, None, commandline, None, None, False, win32process.CREATE_NO_WINDOW, None, None, si)
	
    except:
	print "dddddddddddddddddddddddddd"

def OpenProcess2(procPath, param = ""):
    commandline = "\"" + procPath + "\" " + param
    win32api.WinExec(commandline)
    
def OpenProcess4(procPath, param = ""):
    commandline = "\"" + procPath + "\" " + param
    os.popen(commandline).read()
    
def OpenProcess3(procPath, param = ""):
    commandline = "\"" + procPath + "\" " + param
    os.system(commandline)
  
def OpenProcess5(procPath, param = ""):
    commandline = "\"" + procPath + "\" " + param
    proc = subprocess.Popen(commandline)
    print proc.communicate()[0] 
##    proc.wait()

exePath = "D:\\seqa\\qadev\\src\\CheckListTools\\ATF2.2\\case\\seSmoke\\SESQLiteDecrypt.exe"
para = "C:\\Users\\wangdehe\\AppData\\Roaming\\SogouExplorer\\Extension.db"
para1 = "C:\\Users\\wangdehe\\AppData\\Roaming\\SogouExplorer\\Extension_bak.db"

exePath1 = "C:\\Users\\wangdehe\\Desktop\\testinput.bat"
exePath2 = r"C:\Users\wangdehe\Documents\visual studio 2010\Projects\test\test\bin\Debug\test.exe"

shutil.copy(para1, para)

##OpenProcess0(exePath2, para)    #可以
##OpenProcess1(exePath, para)    #無效-未解密
##OpenProcess2(exePath, para)    #無效-未解密
##OpenProcess3(exePath, para)    #卡住
##OpenProcess4(exePath, para)    #無效-未解密
##OpenProcess5(exePath2, para)    #卡住


暫時定位到標紅的部分,當第二個方法,標紅部分修改爲0-31任意值時,都會出現卡住的現象



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章