def __init__(self, reactor, protocol, command, args, environment, path): self.reactor = reactor self.protocol = protocol self.outBuffer = reactor.AllocateReadBuffer(self.bufferSize) self.errBuffer = reactor.AllocateReadBuffer(self.bufferSize) # This is the buffer for *reading* stdin, which is only done to # determine if the other end of the pipe was closed. self.inBuffer = reactor.AllocateReadBuffer(self.bufferSize) # IO operation classes self.readOutOp = ops.ReadOutOp(self) self.readErrOp = ops.ReadErrOp(self) self.readInOp = ops.ReadInOp(self) self.writeInOp = ops.WriteInOp(self) self.writeBuffer = "" self.writing = False self.finished = False self.offset = 0 self.writeBufferedSize = 0 self.closingStdin = False self.closedStdin = False self.closedStdout = False self.closedStderr = False # Stdio handles self.hChildStdinRd = None self.hChildStdinWr = None self.hChildStdinWrDup = None self.hChildStdoutRd = None self.hChildStdoutWr = None self.hChildStdoutRdDup = None self.hChildStderrRd = None self.hChildStderrWr = None self.hChildStderrRdDup = None self.closedNotifies = 0 # increments to 3 (for stdin, stdout, stderr) self.closed = False # set to true when all 3 handles close self.exited = False # set to true when WFMO thread gets signalled proc handle. See doWaitForProcessExit. # Set the bInheritHandle flag so pipe handles are inherited. saAttr = win32security.SECURITY_ATTRIBUTES() saAttr.bInheritHandle = 1 currentPid = win32api.GetCurrentProcess( ) # -1 which stands for current process self.pid = os.getpid() # unique pid for pipe naming # Create a pipe for the child process's STDOUT. self.stdoutPipeName = r"\\.\pipe\twisted-iocp-stdout-%d-%d-%d" % ( self.pid, counter.next(), time.time()) self.hChildStdoutRd = win32pipe.CreateNamedPipe( self.stdoutPipeName, win32con.PIPE_ACCESS_INBOUND | win32con.FILE_FLAG_OVERLAPPED, # open mode win32con.PIPE_TYPE_BYTE, # pipe mode 1, # max instances self.pipeBufferSize, # out buffer size self.pipeBufferSize, # in buffer size 0, # timeout saAttr) self.hChildStdoutWr = win32file.CreateFile( self.stdoutPipeName, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr, win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 0) # Create noninheritable read handle and close the inheritable read # handle. self.hChildStdoutRdDup = win32api.DuplicateHandle( currentPid, self.hChildStdoutRd, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32api.CloseHandle(self.hChildStdoutRd) self.hChildStdoutRd = self.hChildStdoutRdDup # Create a pipe for the child process's STDERR. self.stderrPipeName = r"\\.\pipe\twisted-iocp-stderr-%d-%d-%d" % ( self.pid, counter.next(), time.time()) self.hChildStderrRd = win32pipe.CreateNamedPipe( self.stderrPipeName, win32con.PIPE_ACCESS_INBOUND | win32con.FILE_FLAG_OVERLAPPED, # open mode win32con.PIPE_TYPE_BYTE, # pipe mode 1, # max instances self.pipeBufferSize, # out buffer size self.pipeBufferSize, # in buffer size 0, # timeout saAttr) self.hChildStderrWr = win32file.CreateFile( self.stderrPipeName, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr, win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 0) # Create noninheritable read handle and close the inheritable read # handle. self.hChildStderrRdDup = win32api.DuplicateHandle( currentPid, self.hChildStderrRd, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32api.CloseHandle(self.hChildStderrRd) self.hChildStderrRd = self.hChildStderrRdDup # Create a pipe for the child process's STDIN. This one is opened # in duplex mode so we can read from it too in order to detect when # the child closes their end of the pipe. self.stdinPipeName = r"\\.\pipe\twisted-iocp-stdin-%d-%d-%d" % ( self.pid, counter.next(), time.time()) self.hChildStdinWr = win32pipe.CreateNamedPipe( self.stdinPipeName, win32con.PIPE_ACCESS_DUPLEX | win32con.FILE_FLAG_OVERLAPPED, # open mode win32con.PIPE_TYPE_BYTE, # pipe mode 1, # max instances self.pipeBufferSize, # out buffer size self.pipeBufferSize, # in buffer size 0, # timeout saAttr) self.hChildStdinRd = win32file.CreateFile( self.stdinPipeName, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr, win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 0) # Duplicate the write handle to the pipe so it is not inherited. self.hChildStdinWrDup = win32api.DuplicateHandle( currentPid, self.hChildStdinWr, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32api.CloseHandle(self.hChildStdinWr) self.hChildStdinWr = self.hChildStdinWrDup # set the info structure for the new process. This is where # we tell the process to use the pipes for stdout/err/in. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdOutput = self.hChildStdoutWr StartupInfo.hStdError = self.hChildStderrWr StartupInfo.hStdInput = self.hChildStdinRd StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # create the process cmdline = quoteArguments(args) self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess( command, # name cmdline, # command line None, # process security attributes None, # primary thread security attributes 1, # handles are inherited 0, # creation flags environment, # if NULL, use parent environment path, # current directory StartupInfo) # STARTUPINFO pointer # close handles which only the child will use win32file.CloseHandle(self.hChildStderrWr) win32file.CloseHandle(self.hChildStdoutWr) win32file.CloseHandle(self.hChildStdinRd) # Begin reading on stdout and stderr, before we have output on them. self.readOutOp.initiateOp(self.hChildStdoutRd, self.outBuffer) self.readErrOp.initiateOp(self.hChildStderrRd, self.errBuffer) # Read stdin which was opened in duplex mode so we can detect when # the child closed their end of the pipe. self.readInOp.initiateOp(self.hChildStdinWr, self.inBuffer) # When the process is done, call connectionLost(). # This function returns right away. Note I call this after # protocol.makeConnection to ensure that the protocol doesn't # have processEnded called before protocol.makeConnection. self.reactor.processWaiter.beginWait(self.reactor, self.hProcess, self) # notify protocol by calling protocol.makeConnection and specifying # ourself as the transport. self.protocol.makeConnection(self)
#p = subprocess.Popen(pname, stdin=subprocess.PIPE,stdout=subprocess.PIPE) #result = p.communicate(input=source) #res = result[0].decode()[0:leng] #print(res) import win32api #日报软件启动 #win32api.ShellExecute(0, 'open', r'C:\Users\Administrator\Desktop\Debug\test.ece', '','',1) import os import win32process #os.startfile("C:/Users/Administrator/Desktop/Debug/test.exe") #win32process.CreateProcess('C:/Users/Administrator/Desktop/Debug/test.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW,None, None, win32process.STARTUPINFO()) import win32event handle = win32process.CreateProcess('C:/Users/Administrator/Desktop/Debug1/test.exe', "C:/Users/Administrator/Desktop/Debug1/test.exe 这是啥", None, None, 0, win32process.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO()) win32event.WaitForSingleObject(handle[0], -1) handle = win32process.CreateProcess('C:/Users/Administrator/Desktop/Debug1/test.exe', "C:/Users/Administrator/Desktop/Debug1/test.exe 结束了", None, None, 0, win32process.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO())
def start_(self, cmd_line, timeout=None, retry_interval=None, create_new_console=False): "Starts the application giving in cmd_line" if timeout is None: timeout = Timings.app_start_timeout if retry_interval is None: retry_interval = Timings.app_start_retry start_info = win32process.STARTUPINFO() # we need to wrap the command line as it can be modified # by the function command_line = cmd_line # Actually create the process dwCreationFlags = 0 if create_new_console: dwCreationFlags = win32con.CREATE_NEW_CONSOLE try: (hProcess, hThread, dwProcessId, dwThreadId) = win32process.CreateProcess( None, # module name command_line, # command line None, # Process handle not inheritable. None, # Thread handle not inheritable. 0, # Set handle inheritance to FALSE. dwCreationFlags, # Creation flags. None, # Use parent's environment block. None, # Use parent's starting directory. start_info) # STARTUPINFO structure. except Exception as exc: # if it failed for some reason message = ('Could not create the process "%s"\n' 'Error returned by CreateProcess: %s') % (cmd_line, str(exc)) raise AppStartError(message) self.process = dwProcessId def AppIdle(): "Return true when the application is ready to start" result = win32event.WaitForInputIdle(hProcess, int(timeout * 1000)) # wait completed successfully if result == 0: return True # the wait returned because it timed out if result == win32con.WAIT_TIMEOUT: return False return bool(self.windows_()) # Wait until the application is ready after starting it try: WaitUntil(timeout, retry_interval, AppIdle) except TimeoutError: pass return self
def checkSchedulerStart(errorHandler, name, isExisted): errorFile = "error.log" listFile = "schList.log" try: XPMode = False version = platform.platform() verReg = re.search('Windows-(\w+)-', version) if verReg != None: if verReg.group(1) == 'XP' or verReg.group(1) == '2003Server': XPMode = True if XPMode: filePath = os.getenv( 'windir') + os.sep + "Tasks" + os.sep + name + ".job" FileFunc.checkFileExist(errorHandler, filePath, isExisted) else: command = "cmd.exe /c chcp 437 | SCHTASKS /QUERY /TN " + "\"" + name + "\" 2>" + errorFile + " 1>" + listFile exePath = "C:\Windows\System32\cmd.exe" handle = win32process.CreateProcess(exePath, command, \ None , None , 0 ,win32process.CREATE_NEW_CONSOLE , None , None , \ win32process.STARTUPINFO()) win32event.WaitForSingleObject(handle[0], -1) time.sleep(1) if isExisted and os.path.getsize(errorFile) > 0: raise Exception("The job \"%s\" does not exist" % (name)) elif not isExisted and os.path.getsize(errorFile) == 0: disableFlag = False if os.path.exists(listFile): fList = codecs.open(listFile, 'r', encoding='utf8') for aLine in fList.readlines(): if aLine.find("Disabled") > -1: disableFlag = True break fList.close() if not disableFlag: raise Exception("The job \"%s\" exists" % (name)) #os.remove(errorFile) #os.remove(listFile) except Exception: if os.path.exists(errorFile): os.remove(errorFile) errorInfo = { Global.ERROR_CALLSTACK: traceback, Global.ERROR_MESSAGE: traceback.format_exc() } errorHandler.handler(errorInfo) return True
def run(self, cmdline): # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create pipes hStdin_r, self.hStdin_w = win32pipe.CreatePipe(sAttrs, 0) self.hStdout_r, hStdout_w = win32pipe.CreatePipe(sAttrs, 0) self.hStderr_r, hStderr_w = win32pipe.CreatePipe(sAttrs, 0) # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdInput = hStdin_r StartupInfo.hStdOutput = hStdout_w StartupInfo.hStdError = hStderr_w StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Mark doesn't support wShowWindow yet. # StartupInfo.dwFlags = StartupInfo.dwFlags | win32process.STARTF_USESHOWWINDOW # StartupInfo.wShowWindow = win32con.SW_HIDE # Create new output read handles and the input write handle. Set # the inheritance properties to FALSE. Otherwise, the child inherits # the these handles; resulting in non-closeable handles to the pipes # being created. pid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle( pid, self.hStdin_w, pid, 0, 0, # non-inheritable!! win32con.DUPLICATE_SAME_ACCESS) # Close the inhertible version of the handle win32file.CloseHandle(self.hStdin_w) self.hStdin_w = tmp tmp = win32api.DuplicateHandle( pid, self.hStdout_r, pid, 0, 0, # non-inheritable! win32con.DUPLICATE_SAME_ACCESS) # Close the inhertible version of the handle win32file.CloseHandle(self.hStdout_r) self.hStdout_r = tmp # start the process. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess( None, # program cmdline, # command line None, # process security attributes None, # thread attributes 1, # inherit handles, or USESTDHANDLES won't work. # creation flags. Don't access the console. 0, # Don't need anything here. # If you're in a GUI app, you should use # CREATE_NEW_CONSOLE here, or any subprocesses # might fall victim to the problem described in: # KB article: Q156755, cmd.exe requires # an NT console in order to perform redirection.. None, # no new environment None, # current directory (stay where we are) StartupInfo) # normally, we would save the pid etc. here... # Child is launched. Close the parents copy of those pipe handles # that only the child should have open. # You need to make sure that no handles to the write end of the # output pipe are maintained in this process or else the pipe will # not close when the child process exits and the ReadFile will hang. win32file.CloseHandle(hStderr_w) win32file.CloseHandle(hStdout_w) win32file.CloseHandle(hStdin_r) self.stdin = os.fdopen(msvcrt.open_osfhandle(self.hStdin_w, 0), "wb") self.stdin.write('hmmmmm\r\n') self.stdin.flush() self.stdin.close() self.stdout = os.fdopen(msvcrt.open_osfhandle(self.hStdout_r, 0), "rb") print("Read on stdout: ", repr(self.stdout.read())) self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb") print("Read on stderr: ", repr(self.stderr.read()))
def _RunAsOnWindowStationDesktop(command_line, security_token, window_station, desktop, env=None, cwd=None, timeout=win32event.INFINITE): """Runs a command as the security token user on given desktop. Args: command_line: Full command line string to run. security_token: Security token that the command run as. window_station: Window station for the new process to run, tpically is "WinSta0", aka the interactive window station. desktop: Desktop that the new process will be associatedw with, typically is 'default'. env: The environment variables to pass to the child process, or None to inherit from parent. cwd: The working directory of the child process, or None to inherit from parent. timeout: How long should wait for child process. 0 means no wait, None means infinitely. Returns: (pid, exit_code, stdout, stderr) tuple. Raises: ImpersonationError: when impersonation failed. """ pipes = _StdoutStderrPipes() si = win32process.STARTUPINFO() si.dwFlags = win32process.STARTF_USESHOWWINDOW | win32con.STARTF_USESTDHANDLES si.wShowWindow = win32con.SW_SHOW si.lpDesktop = '%s\\%s' % (window_station, desktop) si.hStdOutput = pipes.stdout_w si.hStdError = pipes.stderr_w create_flags = (win32process.CREATE_NEW_CONSOLE | win32process.CREATE_UNICODE_ENVIRONMENT) if env: saved_env = dict(os.environ) os.environ.update(env) env_block = win32profile.CreateEnvironmentBlock(security_token, True) (process_handle, unused_thread, pid, unused_thread_id) = win32process.CreateProcessAsUser( security_token, None, command_line, None, None, 1, create_flags, env_block, cwd, si) if env: os.environ.clear() os.environ.update(saved_env) pipes.CloseWriteHandles() if not process_handle: logging.error('Failed to create child process [%s] on [%s\\%s]', command_line, window_station, desktop) raise ImpersonationError( 'Failed to create process [%s] with impersonation: [%s\\%s][%s]' % (command_line, window_station, desktop, cwd)) pipes.ReadAll() logging.info('Child process [%s] created on [%s\\%s]', command_line, window_station, desktop) logging.info('Waiting %s seconds for child process.', timeout) if timeout != win32event.INFINITE: timeout *= 1000 # Convert from seconds to milli-seconds. wait_result = win32event.WaitForSingleObject(process_handle, timeout * 1000) if wait_result == win32event.WAIT_OBJECT_0: exit_code = win32process.GetExitCodeProcess(process_handle) logging.info('Child process exited with code %s.', exit_code) logging.info('Child process STDOUT: %s', pipes.stdout) logging.error('Child process STDERR: %s.', pipes.stderr) return (pid, exit_code, pipes.stdout, pipes.stderr) else: if timeout != 0: logging.warning('Wait for child process timeout in %s seconds', timeout / 1000) return (pid, None, None, None)
def CreateProc(appname, cmdline=None): global cfg #找到winlogon.exe的进程信息,然后复制它的token,再赋权新的token,用新token创建的新进程,就有前台交互权限了 p = getProcess(caption='winlogon.exe')[0] pid = p['pid'] if cfg['debug']: mylog("pid=%d,type=%s" % (pid, type(pid))) #通过winlogon.exe的pid打开进程,获得它的句柄 handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) #通过winlogon.exe的句柄,获得它的令牌(经测试,admin权限运行的程序,只能用TOKEN_QUERY方式打开,service方式运行的程序,有全部权限) token_handle = win32security.OpenProcessToken( handle, win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY | win32con.TOKEN_DUPLICATE) if cfg['debug']: print("winlogon.exe's handle=%s,token=%s" % (handle, token_handle)) res = None #通过winlogon.exe的令牌,复制一个新令牌(经测试,admin权限运行的程序,权限不足,service方式运行的程序,有全部权限) dup_th = win32security.DuplicateTokenEx( token_handle, win32security.SecurityImpersonation, win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary, ) #通过winlogon.exe的pid,获得它的session id(经测试,admin权限运行的程序,没TCB权限,需要service方式运行的程序,有全部权限) curr_session_id = win32ts.ProcessIdToSessionId(pid) if cfg['debug']: print("dup_th=%s" % dup_th) #获得系统默认的程序启动信息(初始化程序所需的,标准输出、桌面选择等信息) startup = win32process.STARTUPINFO() if cfg['debug']: print(startup) #下面的这个win32con.CREATE_NEW_CONSOLE权限必须给,要不后面CreateProcessAsUser时看到执行了,然后程序就没了 priority = win32con.NORMAL_PRIORITY_CLASS | win32con.CREATE_NEW_CONSOLE if cfg['debug']: mylog("in CreateProc(),appname=%s,cmdline=%s" % (appname, cmdline)) (hProcess, hThread, dwProcessId, dwThreadId) = (None, None, None, None) #通过winlogon.exe的session id获得它的console令牌 console_user_token = win32ts.WTSQueryUserToken(curr_session_id) #通过winlogon.exe的console令牌,获得它的环境profile设置信息 environment = win32profile.CreateEnvironmentBlock(console_user_token, False) #给复制出来的token,绑定对应的session id,使之基于和winlogon.exe一样的会话 win32security.SetTokenInformation(dup_th, win32security.TokenSessionId, curr_session_id) #设置调整权限的flag权限 flags = win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY #设置权限1:找到SE_DEBUG_NAME的权限的id,给p1 p1 = win32security.LookupPrivilegeValue(None, win32con.SE_DEBUG_NAME) newPrivileges = [(p1, win32con.SE_PRIVILEGE_ENABLED)] #把复制出来的winlogon.exe的token,增加新权限(也即是SE_DEBUG_NAME权限) win32security.AdjustTokenPrivileges(dup_th, False, newPrivileges) if cfg['debug']: privs = getPrivs(dup_th) mylog("privs=%s" % "\n".join(privs)) #下面准备启动程序需要的重定向的标准输出和标准错误输出的文件句柄,但目前似乎没有重定向成功:( fh_stdout = win32file.CreateFile( os.path.join(app_path, "watchdog.stdout"), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_ALWAYS, win32file.FILE_FLAG_SEQUENTIAL_SCAN, 0) fh_stderr = win32file.CreateFile( os.path.join(app_path, "watchdog.stderr"), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_ALWAYS, win32file.FILE_FLAG_SEQUENTIAL_SCAN, 0) startup.hStdOutput = fh_stdout startup.hStdError = fh_stderr #下面开始尝试用复制好的token:dup_th,并也给了足够的权限的token,然后来启动指定程序 try: (hProcess, hThread, dwProcessId, dwThreadId) = win32process.CreateProcessAsUser( dup_th, appname, cmdline, None, None, True, priority, None, None, startup) except Exception as e: mylog("in CreateProc(),return False,ERROR:%s" % str(e)) return False mylog("%s,%s,%s,%s" % (hProcess, hThread, dwProcessId, dwThreadId)) if dwProcessId == None: #创建进程失败 mylog( "Can not get dwProcessId from win32process.CreateProcessAsUser()") return False try: time.sleep(2) mylog("dwProcessId=%s" % dwProcessId) process = psutil.Process(dwProcessId) except Exception as e: mylog("CreateProc(),try to psutil.Process(),ERROR:%s" % str(e)) mylog("process:%s" % process) return_code = None try: return_code = process.wait(10) except Exception as e: mylog("CreateProc(),try to process.wait(),ERROR:%s" % str(e)) mylog("Maybe Child process Running already , but not quit") mylog("CreateProc return code=%s" % str(return_code))
def start(self, cmd_line, timeout=None, retry_interval=None, create_new_console=False, wait_for_idle=True): """Start the application as specified by cmd_line""" # try to parse executable name and check it has correct bitness if '.exe' in cmd_line and self.backend.name == 'win32': exe_name = cmd_line.split('.exe')[0] + '.exe' _warn_incorrect_binary_bitness(exe_name) if timeout is None: timeout = Timings.app_start_timeout if retry_interval is None: retry_interval = Timings.app_start_retry start_info = win32process.STARTUPINFO() # we need to wrap the command line as it can be modified # by the function command_line = cmd_line # Actually create the process dw_creation_flags = 0 if create_new_console: dw_creation_flags = win32con.CREATE_NEW_CONSOLE try: (h_process, _, dw_process_id, _) = win32process.CreateProcess( None, # module name command_line, # command line None, # Process handle not inheritable. None, # Thread handle not inheritable. 0, # Set handle inheritance to FALSE. dw_creation_flags, # Creation flags. None, # Use parent's environment block. None, # Use parent's starting directory. start_info) # STARTUPINFO structure. except Exception as exc: # if it failed for some reason message = ('Could not create the process "%s"\n' 'Error returned by CreateProcess: %s') % (cmd_line, str(exc)) raise AppStartError(message) self.process = dw_process_id if self.backend.name == 'win32': self.__warn_incorrect_bitness() def app_idle(): """Return true when the application is ready to start""" result = win32event.WaitForInputIdle(h_process, int(timeout * 1000)) # wait completed successfully if result == 0: return True # the wait returned because it timed out if result == win32con.WAIT_TIMEOUT: return False return bool(self.windows()) # Wait until the application is ready after starting it if wait_for_idle and not app_idle(): warnings.warn( 'Application is not loaded correctly (WaitForInputIdle failed)', RuntimeWarning) return self
def processCreate(sName, asArgs): """ Returns a (pid, handle, tid) tuple on success. (-1, None) on failure (logged). """ # Construct a command line. sCmdLine = '' for sArg in asArgs: if sCmdLine == '': sCmdLine += '"' else: sCmdLine += ' "' sCmdLine += sArg sCmdLine += '"' # Try start the process. # pylint: disable=no-member dwCreationFlags = win32con.CREATE_NEW_PROCESS_GROUP oStartupInfo = win32process.STARTUPINFO() # pylint: disable=c-extension-no-member try: (hProcess, hThread, uPid, uTid) = win32process.CreateProcess( sName, # pylint: disable=c-extension-no-member sCmdLine, # CommandLine None, # ProcessAttributes None, # ThreadAttibutes 1, # fInheritHandles dwCreationFlags, None, # Environment None, # CurrentDirectory. oStartupInfo) except: reporter.logXcpt('sName="%s" sCmdLine="%s"' % (sName, sCmdLine)) return (-1, None, -1) # Dispense with the thread handle. try: hThread.Close() # win32api.CloseHandle(hThread); except: reporter.logXcpt() # Try get full access to the process. try: hProcessFullAccess = win32api.DuplicateHandle( # pylint: disable=c-extension-no-member win32api.GetCurrentProcess(), # pylint: disable=c-extension-no-member hProcess, win32api.GetCurrentProcess(), # pylint: disable=c-extension-no-member win32con.PROCESS_TERMINATE | win32con.PROCESS_QUERY_INFORMATION | win32con.SYNCHRONIZE | win32con.DELETE, False, 0) hProcess.Close() # win32api.CloseHandle(hProcess); hProcess = hProcessFullAccess except: reporter.logXcpt() reporter.log2('processCreate -> %#x, hProcess=%s %#x' % ( uPid, hProcess, hProcess.handle, )) return (uPid, hProcess, uTid)
def on_edit(self): win32process.CreateProcess(None,"ui.exe", None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO())
print 'CreateDesktop failed, err=%s' % windll.kernel32.GetLastError() sys.exit(20) #### Create a job JOB_NAME = 'UniqueJob-%s' % os.getpid() try: hJob = win32job.CreateJobObject(None, JOB_NAME) except pywintypes.error, e: print 'CreateJobObject failed, err=%s' % e[0] sys.exit(25) #### Create the process startupInfo = win32process.STARTUPINFO() startupInfo.lpDesktop = DESKTOP_NAME try: processInfo = win32process.CreateProcess(None, childCmdLine, None, None, True, win32con.CREATE_SUSPENDED, None, None, startupInfo) except pywintypes.error, e: print 'CreateProcess failed, err=%s' % e[0] sys.exit(30) hProcess = processInfo[0] #### Associate the process with the job try:
def ditmake(self,name,type): print(type,name) if type == 'start' and name =="windows": window.minimize() handle = win32process.CreateProcess('BotPlace/Botit Cloud/Botit Cloud.exe', '',None , None ,0, win32process. CREATE_NO_WINDOW , None , None ,win32process.STARTUPINFO()) print('Destroying window..') return if (type == 'start' and name =="developer" )or (type == 'updateme' and name =="developer"): window.minimize() if type == "start": subprocess.call(["BotPlace/BotPlace Develop Tool/Bot Place Developer Tool.exe"]) else: subprocess.call(["BotPlace/BotPlace Develop Tool/Bot Place Developer Tool.exe", "Update"]) return if type == 'start' and name =="automirror": window.minimize() handle = win32process.CreateProcess('BotPlace/Auto Mirror/Auto Mirror.exe', '',None , None ,0, win32process. CREATE_NO_WINDOW , None , None ,win32process.STARTUPINFO()) return # if type == "updateme": # print('need update') # if type == "grayme": # print('need DL') if name =="windows": appname = "Botit Cloud" appver = botver data1="Automatic Bot Client" data2="Self Deploy Images and Functions" data3="Super Light and easy to use" data4="No Screen or Mouse Use to bot." if name =="developer": appname = "BotPlace Developer Tool" appver = devver data1="Full Automation Builder Framework" data2="All Code Needed is Removed." data3="Everything is Fully automated" data4="Multi Support for Python,AHK,HTML,CSS,JS" if name =="automirror": appname = "Auto-Mirror" appver = autover data1="Automatic Mirror for Any Android Phone" data2="Allow Wifi and USB control Mirror" data3="Very Low " data4="No logs no data send. Fully local!" dict = {'idname': name,'typer':type,'appname':appname,'appver':appver,'data1':data1,'data2':data2,'data3':data3,'data4':data4} mydiv=''' <div class="installer" id="{idname}"> <div class="info" ></div> <div class="details"> <p>{appname}</p> <span>{appver}</span> <ul> <li>{data1}</li> <li>{data2}</li> <li>{data3}</li> <li>{data4}</li> </ul> </div> <label for="progressWindows"><input type="radio" id="progressWindows" onclick="pywebview.api.{typer}('{idname}')"/><span></span></label> <a class="close" href="#platforms"></a> </div> '''.format(**dict) dict = {'name': 'appdits','change':'innerHTML','element':mydiv} testvar = ''' document.getElementById('{name}').{change} = `{element}` '''.format(**dict) window.evaluate_js(testvar)
def start_prog(path): global df df = pd.read_excel(path) df['start_time'] = df['start_time'].astype(str) while True: now_time_str = str(datetime.datetime.now().time()).split('.')[0] time.sleep(0.5) print '%s'%now_time_str df_to_start = df.query("start_time == @now_time_str") for i in range(len(df_to_start)): d = df_to_start.iloc[i,:].to_dict() x = int(d['x']) y = int(d['y']) dx = int(d['dx']) dy = int(d['dy']) si = win32process.STARTUPINFO() si.dwX, si.dwY = [x, y] xySize = [dx, dy] si.dwXSize, si.dwYSize = xySize si.dwFlags ^= STARTF_USEPOSITION | STARTF_USESIZE if pd.isnull(d['params']): cmd_line = u"""%s"""%d['path'] else: cmd_line = u"""%s %s"""%(d['path'], d['params']) params = (None, cmd_line, None , None , 0 , 16 , None , None ,si ) hProcess, hThread, dwProcessId, dwThreadId = win32process.CreateProcess(*params) # 如果不是cmd程序,还要调用Move,否则就结束 # # 新进程的时候,能得到pid,已经有进程了,得到的不是pid… print hProcess, hThread, dwProcessId, dwThreadId time.sleep(int(d['sleep_time'])) if d['is_cmd'] == 'y': pass # 因为cmd可以启动时指定位置 else: # 得到当前handle、pid、窗口名称的信息 window_info_df = window_name_utils.get_window_info() if d['use_caption'] == 'n': # 用pid hwnd = window_info_df.loc[window_info_df['pid']==dwProcessId, 'handle'].values[0] elif d['use_caption'] == 'y': print u'通过窗口名称获得handle' handles = window_info_df.loc[window_info_df['caption']==d['caption'], 'handle'].values if len(handles) == 1: # 唯一标题,直接根据hwnd移动 hwnd = handles[0] elif len(handles) > 1: # 标题名字有重复的,根据 createProcess 得到的pid, 再找handle, 移动 # 先假设这个pid只会有一个handle hwnd = window_info_df.loc[(window_info_df['pid'] == dwProcessId) & ( (window_info_df['caption'] == d['caption'])), 'handle'].values[0] # ======== ShowWindow(hwnd, SW_RESTORE) # 1. 还原 # 有些窗口不能还原?!!! time.sleep(1) MoveWindow(hwnd, x, y, dx, dy, True) # 2. 移动 if d['need_max'] == 'y': time.sleep(1) ShowWindow(hwnd, SW_MAXIMIZE) # 最大化
def open_url(self, url, page_cls=None): '''打开一个url,返回对应的webpage实例类 :params url: url :type url: str :params page_cls: page实例类 :type page_cls: class ''' ie_path = IEBrowser.get_path() # -e可以实现以新进程的方式打开ie pid = win32process.CreateProcess(None, '%s -e %s ' % (ie_path, url), None, None, 0, win32con.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO())[2] if not pid in self._pid_list: self._pid_list.append(pid) handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) win32event.WaitForInputIdle(handle, 10000) return self._get_page_cls(pid, page_cls)
def __init__(self, reactor, protocol, command, args, environment, path): _pollingfile._PollingTimer.__init__(self, reactor) self.protocol = protocol # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create the pipes which will connect to the secondary process self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0) self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0) hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0) win32pipe.SetNamedPipeHandleState(self.hStdinW, win32pipe.PIPE_NOWAIT, None, None) # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdOutput = hStdoutW StartupInfo.hStdError = hStderrW StartupInfo.hStdInput = hStdinR StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Create new handles whose inheritance property is false currentPid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle(currentPid, self.hStdoutR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStdoutR) self.hStdoutR = tmp tmp = win32api.DuplicateHandle(currentPid, self.hStderrR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStderrR) self.hStderrR = tmp tmp = win32api.DuplicateHandle(currentPid, self.hStdinW, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStdinW) self.hStdinW = tmp # Add the specified environment to the current environment - this is # necessary because certain operations are only supported on Windows # if certain environment variables are present. env = os.environ.copy() env.update(environment or {}) cmdline = quoteArguments(args) # TODO: error detection here. def doCreate(): self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess( command, cmdline, None, None, 1, 0, env, path, StartupInfo) try: doCreate() except pywintypes.error, pwte: if not _invalidWin32App(pwte): # This behavior isn't _really_ documented, but let's make it # consistent with the behavior that is documented. raise OSError(pwte) else: # look for a shebang line. Insert the original 'command' # (actually a script) into the new arguments list. sheb = _findShebang(command) if sheb is None: raise OSError( "%r is neither a Windows executable, " "nor a script with a shebang line" % command) else: args = list(args) args.insert(0, command) cmdline = quoteArguments(args) origcmd = command command = sheb try: # Let's try again. doCreate() except pywintypes.error, pwte2: # d'oh, failed again! if _invalidWin32App(pwte2): raise OSError( "%r has an invalid shebang line: " "%r is not a valid executable" % ( origcmd, sheb)) raise OSError(pwte2)
def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session): """Execute program""" assert not pass_fds, "pass_fds not supported on Windows." if not isinstance(args, str): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = win32process.STARTUPINFO() if -1 not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= win32process.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags |= win32process.STARTF_USESHOWWINDOW startupinfo.wShowWindow = win32process.SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = '{} /c "{}"'.format(comspec, args) # Start the process try: hp, ht, pid, tid = win32process.CreateProcessAsUser(self._token, executable, args, # no special security None, None, int(not close_fds), creationflags, env, os.fspath(cwd) if cwd is not None else None, startupinfo) finally: # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread != -1: p2cread.Close() if c2pwrite != -1: c2pwrite.Close() if errwrite != -1: errwrite.Close() if hasattr(self, '_devnull'): os.close(self._devnull) try: # Retain the process handle, but close the thread handle self._child_created = True # Popen stores the win handle as an int, not as a PyHandle self._handle = Handle(hp.Detach()) self.pid = pid finally: CLOSEHANDLE(ht)
def get_handle(app_info): return win32process.CreateProcess(app_info.path, '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO())
def take_screenshot(): ret = False ScreenShot.init_globals() if ScreenShot.DISABLE_SSHOT: p("}}ybSkipping screen shot - disabled by .disable_sshot file}}xx", log_level=2) return # Find the logged in user and run the sshot.exe app cmd = os.path.join(util.BINARIES_FOLDER, "sshot\\sshot.exe") p("}}gnTrying to run " + cmd + "}}xx", log_level=4) user_token = UserAccounts.get_active_user_token() if user_token is None: p("}}ynUnable to get user token - screen locked?}}xx", log_level=2) return ret sidObj, intVal = win32security.GetTokenInformation( user_token, win32security.TokenUser) #source = win32security.GetTokenInformation(tokenh, TokenSource) if sidObj: accountName, domainName, accountTypeInt = \ win32security.LookupAccountSid(".", sidObj) else: p("}}rnUnable to get User Token! }}xx", log_level=1) return None #p("}}gnFound User Token: " + str(user_token) + "}}xx", log_level=5) # If user is in the administrators group, skip taking the sshot if UserAccounts.is_in_admin_group(accountName): p("}}mbUser (" + accountName + ") is in admin group, skipping screen shot...}}xx") return True p("}}gnRunning As: " + accountName + "}}xx", log_level=2) # Put this token in the logged in session #win32security.SetTokenInformation(user_token_copy, win32security.TokenSessionId, session_id) # Use win create process function si = win32process.STARTUPINFO() si.dwFlags = win32process.STARTF_USESHOWWINDOW si.wShowWindow = win32con.SW_NORMAL # si.lpDesktop = "WinSta0\Default" si.lpDesktop = "WinSta0\\Default" # Setup envinroment for the user environment = win32profile.CreateEnvironmentBlock(user_token, False) try: ( hProcess, hThread, dwProcessId, dwThreadId ) = win32process.CreateProcessAsUser( user_token, None, # AppName (really command line, blank if cmd line supplied) "\"" + cmd + "\"", # Command Line (blank if app supplied) None, # Process Attributes None, # Thread Attributes 0, # Inherits Handles win32con. NORMAL_PRIORITY_CLASS, # or win32con.CREATE_NEW_CONSOLE, environment, # Environment os.path.dirname(cmd), # Curr directory si) # Startup info p("Process Started: " + str(dwProcessId), log_level=5) p(hProcess, log_level=5) ret = True except Exception as e: p("}}rnError launching process:}}xx\n" + str(e), log_level=1) # Cleanup user_token.close() # else: # # Not logged in as system user, run as current user # try: # timeout = 10 # 10 seconds? # # Log an error if the process doesn't return 0 # # stdout=PIPE and stderr=STDOUT instead of capture_output=True # p("}}gnRunning as current user " + user_name + "}}xx") # proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,timeout=timeout, check=False) # if (proc.returncode == 0): # p("Command Results: " + cmd + "\n" + proc.stdout.decode()) # ret = True # else: # p("*** Command Failed!: " + cmd + "(" + str(proc.returncode) + ") \n" + proc.stdout.decode()) # except Exception as ex: # p("*** Command Exception! " + cmd + " \n" + \ # str(ex)) if ret is True: p("}}gnSnapped.}}xx", log_level=3) return ret
def create_process(self, path): _, _, process_id, _ = win32process.CreateProcess( None, path, None, None, 0, win32con.NORMAL_PRIORITY_CLASS, None, None, win32process.STARTUPINFO()) return process_id
def openconsole(input,path="E:\\shared\\install.bat",waittime=-1): try: inputnumber=str(input) handle = win32process.CreateProcess(path, path+' '+inputnumber, None , None , 0 ,win32process.CREATE_NEW_CONSOLE , None , None ,win32process.STARTUPINFO()) tm=win32event.WaitForSingleObject(handle[0], waittime) print(tm) return True except Exception as err: print('打开install.bat时有错误产生,错误是:%s'%str(err)) return False
def runScreenShotApp(self): global DISABLE_SSHOT if DISABLE_SSHOT == True: return # Get the session id for the console session_id = win32ts.WTSGetActiveConsoleSessionId() if session_id == 0xffffffff: # User not logged in right now? logging.info("No console user") return None logging.info("Got Console: " + str(session_id)) # Login to the terminal service to get the user token for the console id svr = win32ts.WTSOpenServer(".") user_token = win32ts.WTSQueryUserToken(session_id) logging.info("User Token " + str(user_token)) # Copy the token user_token_copy = win32security.DuplicateTokenEx( user_token, win32security.SecurityImpersonation, win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary) # Put this token in the logged in session win32security.SetTokenInformation(user_token_copy, win32security.TokenSessionId, session_id) # Switch to the user #win32security.ImpersonateLoggedOnUser(user_token) #logging.info("Impersonating " + win32api.GetUserName()) # Run the screen shot app app_path = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) #cmd = os.path.join(app_path, "sshot\\dist\\sshot.exe") cmd = "c:\\programdata\\ope\\bin\\sshot.exe" #cmd = "cmd.exe" logging.info("Running sshot app " + cmd) # Use win create process function si = win32process.STARTUPINFO() si.dwFlags = win32process.STARTF_USESHOWWINDOW si.wShowWindow = win32con.SW_NORMAL #si.lpDesktop = "WinSta0\Default" si.lpDesktop = "" try: ( hProcess, hThread, dwProcessId, dwThreadId ) = win32process.CreateProcessAsUser( user_token_copy, None, # AppName (really command line, blank if cmd line supplied) "\"" + cmd + "\"", # Command Line (blank if app supplied) None, # Process Attributes None, # Thread Attributes 0, # Inherits Handles win32con. NORMAL_PRIORITY_CLASS, # or win32con.CREATE_NEW_CONSOLE, None, # Environment os.path.dirname(cmd), # Curr directory si) # Startup info logging.info("Process Started: " + str(dwProcessId)) logging.info(hProcess) except Exception as e: logging.info("Error launching process: " + str(e)) #logging.info(os.system(cmd)) # Return us to normal security #win32security.RevertToSelf() # Cleanup win32ts.WTSCloseServer(svr) user_token.close() user_token_copy.close() return
import os import time import win32process import psutil handle = win32process.CreateProcess('p1.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) while True: time.sleep(10) try: p = psutil.Process(handle[2]) print(p.status) except: handle = win32process.CreateProcess('p1.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) print('restart p1') p = psutil.Process(handle[2]) print(p.status)
def runas_system(cmd, username, password): # This only works as system, when salt is running as a service for example # Check for a domain domain = '.' if '@' in username: username, domain = username.split('@') if '\\' in username: domain, username = username.split('\\') # Load User and Get Token token = win32security.LogonUser(username, domain, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) # Load the User Profile handle_reg = win32profile.LoadUserProfile(token, {'UserName': username}) try: # Get Unrestricted Token (UAC) if this is an Admin Account elevated_token = win32security.GetTokenInformation( token, win32security.TokenLinkedToken) # Get list of privileges this token contains privileges = win32security.GetTokenInformation( elevated_token, win32security.TokenPrivileges) # Create a set of all privileges to be enabled enable_privs = set() for luid, flags in privileges: enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) # Enable the privileges win32security.AdjustTokenPrivileges(elevated_token, 0, enable_privs) except win32security.error as exc: # User doesn't have admin, use existing token if exc[0] == winerror.ERROR_NO_SUCH_LOGON_SESSION \ or exc[0] == winerror.ERROR_PRIVILEGE_NOT_HELD: elevated_token = token else: raise # Get Security Attributes security_attributes = win32security.SECURITY_ATTRIBUTES() security_attributes.bInheritHandle = 1 # Create a pipe to set as stdout in the child. The write handle needs to be # inheritable. stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0) stdin_read = make_inheritable(stdin_read) stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0) stdout_write = make_inheritable(stdout_write) stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0) stderr_write = make_inheritable(stderr_write) # Get startup info structure startup_info = win32process.STARTUPINFO() startup_info.dwFlags = win32con.STARTF_USESTDHANDLES startup_info.hStdInput = stdin_read startup_info.hStdOutput = stdout_write startup_info.hStdError = stderr_write # Get User Environment user_environment = win32profile.CreateEnvironmentBlock(token, False) # Build command cmd = 'cmd /c {0}'.format(cmd) # Run command and return process info structure procArgs = (None, cmd, security_attributes, security_attributes, 1, 0, user_environment, None, startup_info) hProcess, hThread, PId, TId = \ win32process.CreateProcessAsUser(elevated_token, *procArgs) if stdin_read is not None: stdin_read.Close() if stdout_write is not None: stdout_write.Close() if stderr_write is not None: stderr_write.Close() hThread.Close() # Initialize ret and set first element ret = {'pid': PId} # Get Standard Out fd_out = msvcrt.open_osfhandle(stdout_read, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_out, 'r') as f_out: ret['stdout'] = f_out.read() # Get Standard Error fd_err = msvcrt.open_osfhandle(stderr_read, os.O_RDONLY | os.O_TEXT) with os.fdopen(fd_err, 'r') as f_err: ret['stderr'] = f_err.read() # Get Return Code if win32event.WaitForSingleObject( hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0: exitcode = win32process.GetExitCodeProcess(hProcess) ret['retcode'] = exitcode # Close handle to process win32api.CloseHandle(hProcess) # Unload the User Profile win32profile.UnloadUserProfile(token, handle_reg) return ret
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software") key = win32api.RegOpenKey(key, "Jabber") key = win32api.RegOpenKey(key, "Exodus") try: restart = win32api.RegOpenKey(key, "Restart") except: sys.exit(0) try: keys = [] for i in range(0, win32api.RegQueryInfoKey(restart)[0]): keys.append(win32api.RegEnumKey(restart, i)) for subkey in keys: skey = win32api.RegOpenKey(restart, subkey) cmdline = win32api.RegQueryValueEx(skey, "cmdline")[0] cwd = win32api.RegQueryValueEx(skey, "cwd")[0] print cmdline print cwd sui = win32process.STARTUPINFO() win32process.CreateProcess(None, cmdline, None, None, False, 0, None, cwd, sui) win32api.RegDeleteKey(restart, subkey) win32api.RegCloseKey(restart) win32api.RegDeleteKey(key, "Restart") except Exception, e: print traceback.print_exc() sys.exit(0) # not an error
def TBStar_TBLogin(un, pw): try: global_TB.status = 1 if "TradeBlazer.exe" not in os.popen( 'tasklist /FI "IMAGENAME eq TradeBlazer.exe"').read(): #打开TB handle = win32process.CreateProcess( global_TB.path + 'TradeBlazer.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, global_TB.path, win32process.STARTUPINFO()) #打开TB,获得其句柄 time.sleep(21) Log('打开TB') #数据重置 win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'Button', '数据重置'), win32con.BM_CLICK, 1, 0) time.sleep(1) win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', '数据重置'), 0, 'Button', '重置(&R)'), win32con.BM_CLICK, 1, 0) time.sleep(1) win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', '确认'), 0, 'Button', '是(&Y)'), win32con.BM_CLICK, 1, 0) time.sleep(1) win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', '提示'), 0, 'Button', '确定'), win32con.BM_CLICK, 1, 0) time.sleep(1) #登录框 win32gui.SendMessage( win32gui.FindWindowEx( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'ComboBox', None), 0, 'Edit', None), win32con.WM_SETTEXT, 0, un) time.sleep(1) win32gui.SendMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'Edit', None), win32con.WM_SETTEXT, 0, pw) time.sleep(1) win32gui.SendMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'Button', '登录(&L)'), win32con.BM_CLICK, 1, 0) ##global global_TB.status global_TB.status = 2 Log(str('登录柜台')) time.sleep(28) #取得TB句柄 win32gui.EnumWindows(handle_window, '交易开拓者') #time.sleep(2) #取得帐户列表数目 global_TB.Accounts = win32gui.SendMessage( win32gui.FindWindowEx( win32gui.FindWindowEx( win32gui.FindWindowEx( global_TB.TB_handle, win32gui.FindWindowEx(global_TB.TB_handle, 0, 'AfxControlBar110', None), 'AfxControlBar110', None), 0, None, '帐户管理'), 0, 'SysListView32', None), LVM_GETITEMCOUNT) global_TB.Trade = 0 except Exception as e: Log(str(e))
(ROOT, ROOT, ROOT)) os.system( 'limbo -t Loader -I%s/module %s/module/runt.m > %s/libinterp/loadermod.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -t Freetype -I%s/module %s/module/runt.m > %s/libinterp/freetypemod.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -t Bench -I%s/module %s/module/bench.m > %s/libinterp/benchmod.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -a -I%s/module %s/module/bench.m > %s/libinterp/bench.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -a -I%s/module %s/module/srvrunt.b >%s/emu/port/srv.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -t Srv -I%s/module %s/module/srvrunt.b >%s/emu/port/srvm.h' % (ROOT, ROOT, ROOT)) cmd = r'%s -o %s %s %s %s %s' % (CC, OUT, DEFINES, INCLUDES, FNAMES, LIBS) #print cmd #sys.exit() #os.system(cmd) import win32process, win32event hProcess, hThread, dwPid, dwTid = win32process.CreateProcess( None, cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO()) win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
def __init__(self, cmd, login=None, hStdin=None, hStdout=None, hStderr=None, show=1, xy=None, xySize=None, desktop=None): """ Create a Windows process. cmd: command to run login: run as user 'Domain\nUser\nPassword' hStdin, hStdout, hStderr: handles for process I/O; default is caller's stdin, stdout & stderr show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...) xy: window offset (x, y) of upper left corner in pixels xySize: window size (width, height) in pixels desktop: lpDesktop - name of desktop e.g. 'winsta0\\default' None = inherit current desktop '' = create new desktop if necessary User calling login requires additional privileges: Act as part of the operating system [not needed on Windows XP] Increase quotas Replace a process level token Login string must EITHER be an administrator's account (ordinary user can't access current desktop - see Microsoft Q165194) OR use desktop='' to run another desktop invisibly (may be very slow to startup & finalize). """ si = win32process.STARTUPINFO() si.dwFlags = (win32con.STARTF_USESTDHANDLES ^ win32con.STARTF_USESHOWWINDOW) if hStdin is None: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdin if hStdout is None: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdout if hStderr is None: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStderr si.wShowWindow = show if xy is not None: si.dwX, si.dwY = xy si.dwFlags ^= win32con.STARTF_USEPOSITION if xySize is not None: si.dwXSize, si.dwYSize = xySize si.dwFlags ^= win32con.STARTF_USESIZE if desktop is not None: si.lpDesktop = desktop procArgs = ( None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32process.CREATE_NEW_CONSOLE, # dwCreationFlags None, # newEnvironment None, # currentDirectory si) # startupinfo if login is not None: hUser = logonUser(login) win32security.ImpersonateLoggedOnUser(hUser) procHandles = win32process.CreateProcessAsUser(hUser, *procArgs) win32security.RevertToSelf() else: procHandles = win32process.CreateProcess(*procArgs) self.hProcess, self.hThread, self.PId, self.TId = procHandles
def create_process(process_path): return win32process.CreateProcess(None, process_path, None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO())
def __init__(self, reactor, protocol, command, args, environment, path): """ Create a new child process. """ _pollingfile._PollingTimer.__init__(self, reactor) BaseProcess.__init__(self, protocol) # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create the pipes which will connect to the secondary process self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0) self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0) hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0) win32pipe.SetNamedPipeHandleState(self.hStdinW, win32pipe.PIPE_NOWAIT, None, None) # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdOutput = hStdoutW StartupInfo.hStdError = hStderrW StartupInfo.hStdInput = hStdinR StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Create new handles whose inheritance property is false currentPid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle(currentPid, self.hStdoutR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStdoutR) self.hStdoutR = tmp tmp = win32api.DuplicateHandle(currentPid, self.hStderrR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStderrR) self.hStderrR = tmp tmp = win32api.DuplicateHandle(currentPid, self.hStdinW, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStdinW) self.hStdinW = tmp # Add the specified environment to the current environment - this is # necessary because certain operations are only supported on Windows # if certain environment variables are present. env = os.environ.copy() env.update(environment or {}) env = { os.fsdecode(key): os.fsdecode(value) for key, value in env.items() } # Make sure all the arguments are Unicode. args = [os.fsdecode(x) for x in args] cmdline = quoteArguments(args) # The command, too, needs to be Unicode, if it is a value. command = os.fsdecode(command) if command else command path = os.fsdecode(path) if path else path # TODO: error detection here. See #2787 and #4184. def doCreate(): flags = win32con.CREATE_NO_WINDOW self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess( command, cmdline, None, None, 1, flags, env, path, StartupInfo) try: doCreate() except pywintypes.error as pwte: if not _invalidWin32App(pwte): # This behavior isn't _really_ documented, but let's make it # consistent with the behavior that is documented. raise OSError(pwte) else: # look for a shebang line. Insert the original 'command' # (actually a script) into the new arguments list. sheb = _findShebang(command) if sheb is None: raise OSError("%r is neither a Windows executable, " "nor a script with a shebang line" % command) else: args = list(args) args.insert(0, command) cmdline = quoteArguments(args) origcmd = command command = sheb try: # Let's try again. doCreate() except pywintypes.error as pwte2: # d'oh, failed again! if _invalidWin32App(pwte2): raise OSError("%r has an invalid shebang line: " "%r is not a valid executable" % (origcmd, sheb)) raise OSError(pwte2) # close handles which only the child will use win32file.CloseHandle(hStderrW) win32file.CloseHandle(hStdoutW) win32file.CloseHandle(hStdinR) # set up everything self.stdout = _pollingfile._PollableReadPipe( self.hStdoutR, lambda data: self.proto.childDataReceived(1, data), self.outConnectionLost, ) self.stderr = _pollingfile._PollableReadPipe( self.hStderrR, lambda data: self.proto.childDataReceived(2, data), self.errConnectionLost, ) self.stdin = _pollingfile._PollableWritePipe(self.hStdinW, self.inConnectionLost) for pipewatcher in self.stdout, self.stderr, self.stdin: self._addPollableResource(pipewatcher) # notify protocol self.proto.makeConnection(self) self._addPollableResource(_Reaper(self))
def get_python_exe(): import _winreg with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\Meta', 0, _winreg.KEY_READ) as key: meta_path = _winreg.QueryValueEx(key, 'META_PATH')[0] return os.path.join(meta_path, r'bin\Python27\Scripts\python.exe') if __name__ == '__main__': command_line = "\"" + get_python_exe( ) + "\" scripts\simulate.py --tool Dymola" sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = True startup = win32process.STARTUPINFO() startup.dwFlags += win32process.STARTF_USESTDHANDLES startup.hStdError = startup.hStdOutput = win32file.CreateFile( "test_dymola_output.txt", win32file.GENERIC_WRITE, 0, sa, win32file.CREATE_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None) startup.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) (hProcess, hThread, processId, threadId) = win32process.CreateProcess( None, command_line, None, None, True, win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup) assert not win32job.IsProcessInJob(hProcess, None) hJob = win32job.CreateJobObject(None, "") extended_info = win32job.QueryInformationJobObject( hJob, win32job.JobObjectExtendedLimitInformation)