def main(): if sys.argv[1] == "child": if sys.argv[2] == "windows": import win32api as api, win32process as proc info = proc.STARTUPINFO() info.hStdInput = api.GetStdHandle(api.STD_INPUT_HANDLE) info.hStdOutput = api.GetStdHandle(api.STD_OUTPUT_HANDLE) info.hStdError = api.GetStdHandle(api.STD_ERROR_HANDLE) python = sys.executable scriptDir = os.path.dirname(__file__) scriptName = os.path.basename(__file__) proc.CreateProcess( None, " ".join((python, scriptName, "grandchild")), None, None, 1, 0, os.environ, scriptDir, info, ) else: if os.fork() == 0: grandchild() else: grandchild()
def __init__(self, proto): """ Start talking to standard IO with the given protocol. Also, put it stdin/stdout/stderr into binary mode. """ from lib.twisted.internet import reactor for stdfd in range(0, 1, 2): msvcrt.setmode(stdfd, os.O_BINARY) _pollingfile._PollingTimer.__init__(self, reactor) self.proto = proto hstdin = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) hstdout = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) self.stdin = _pollingfile._PollableReadPipe(hstdin, self.dataReceived, self.readConnectionLost) self.stdout = _pollingfile._PollableWritePipe(hstdout, self.writeConnectionLost) self._addPollableResource(self.stdin) self._addPollableResource(self.stdout) self.proto.makeConnection(self)
def CreateProcess(cmd, hStdInput, hStdOutput, hStdError): """Creates a new process which uses the specified handles for its standard input, output, and error. The handles must be inheritable. 0 can be passed as a special handle indicating that the process should inherit the current process's input, output, or error streams, and None can be passed to discard the child process's output or to prevent it from reading any input.""" # initialize new process's startup info si = win32process.STARTUPINFO() si.dwFlags = win32process.STARTF_USESTDHANDLES if hStdInput == 0: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdInput if hStdOutput == 0: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdOutput if hStdError == 0: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStdError # create the process phandle, pid, thandle, tid = win32process.CreateProcess \ ( None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32con.NORMAL_PRIORITY_CLASS, # dwCreationFlags None, # newEnvironment None, # currentDirectory si # startupinfo ) if hStdInput and hasattr(hStdInput, 'Close'): hStdInput.Close() if hStdOutput and hasattr(hStdOutput, 'Close'): hStdOutput.Close() if hStdError and hasattr(hStdError, 'Close'): hStdError.Close() return phandle, pid, thandle, tid
def run_label_img(self): if (self.DIR_PATH == 'None'): return "No directory chosen" info = proc.STARTUPINFO() info.hStdInput = api.GetStdHandle(api.STD_INPUT_HANDLE) info.hStdOutput = api.GetStdHandle(api.STD_OUTPUT_HANDLE) info.hStdError = api.GetStdHandle(api.STD_ERROR_HANDLE) python = sys.executable scriptDir = os.path.dirname(self.DIR_PATH) scriptName = os.path.basename(self.DIR_PATH) # print(scriptName) proc.CreateProcess(None, " ".join((python, scriptName, "grandchild")), None, None, 1, 0, os.environ, scriptDir, info) sys.stdout.flush()
def __init__(self, parent=None): super().__init__(parent) self.m_qin = QtCore.QFile() self.m_qin.open( sys.stdin.fileno(), QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Unbuffered ) if platform.system() == "Windows": import win32api if sys.platform == "win32": import os import msvcrt if platform.python_implementation() == "PyPy": os.fdopen(fh.fileno(), "wb", 0) else: msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) self.m_notifier = QtCore.QWinEventNotifier( win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) ) else: self.m_notifier = QtCore.QSocketNotifier( sys.stdin.fileno(), QtCore.QSocketNotifier.Read, self ) self.m_notifier.activated.connect(self.readyRead)
def __init__(self, proto): from twisted.internet import reactor _pollingfile._PollingTimer.__init__(self, reactor) self.proto = proto hstdin = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) hstdout = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) self.stdin = _pollingfile._PollableReadPipe(hstdin, self.dataReceived, self.readConnectionLost) self.stdout = _pollingfile._PollableWritePipe(hstdout, self.writeConnectionLost) self._addPollableResource(self.stdin) self._addPollableResource(self.stdout) self.proto.makeConnection(self)
def _fix_up_win_console_freeze(): import win32api import ctypes try: win32api.SetConsoleTitle("Pyarmor Webui") # Disable quick edit in CMD, as it can freeze the application handle = win32api.GetStdHandle(-10) if handle != -1 and handle is not None: ctypes.windll.kernel32.SetConsoleMode(handle, 128) except Exception: pass
def run_os_command_impersonated(cmd, user, password, domain='.'): si = win32process.STARTUPINFO() out_handle, err_handle, out_file, err_file = _create_tmp_files() ok, si.hStdInput = _safe_duplicate_handle( win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)) if not ok: raise Exception("Unable to create StdInput for child process") ok, si.hStdOutput = _safe_duplicate_handle(out_handle) if not ok: raise Exception("Unable to create StdOut for child process") ok, si.hStdError = _safe_duplicate_handle(err_handle) if not ok: raise Exception("Unable to create StdErr for child process") si.dwFlags = win32process.STARTF_USESTDHANDLES si.lpDesktop = "" user_token = win32security.LogonUser(user, domain, password, win32con.LOGON32_LOGON_SERVICE, win32con.LOGON32_PROVIDER_DEFAULT) primary_token = win32security.DuplicateTokenEx( user_token, win32security.SecurityImpersonation, 0, win32security.TokenPrimary) info = win32process.CreateProcessAsUser(primary_token, None, cmd, None, None, 1, 0, None, None, si) hProcess, hThread, dwProcessId, dwThreadId = info hThread.Close() try: win32event.WaitForSingleObject(hProcess, win32event.INFINITE) except KeyboardInterrupt: pass out, err = _get_files_output(out_file, err_file) exitcode = win32process.GetExitCodeProcess(hProcess) return exitcode, out, err
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
path = "D:\Elik\HW_Golan\Temporary Internet Files" changeHandle = win32file.FindFirstChangeNotification( path, # where to look for True, # looking for changes not only in this directory, but in sub-directories too win32con. FILE_NOTIFY_CHANGE_FILE_NAME # looking for recently added / deleted files ) print "waiting for changes on hadle: " + str(changeHandle) # navigation to link with win32com.client: ieApp = win32com.client.Dispatch("InternetExplorer.Application") #ieApp.Visible = True ieApp.Navigate('http://google.com/search?q=frc&tbm=isch') # stop_handles holds one handle for the notifications and another one for standard winapi input. the second handle waits for input from the keyboard and is used to stop the 'while true' loop by cliking on any key stop_handles = [changeHandle, win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)] # before = os.listdir(path) before = walk(path) while True: # result = return value form waitfor... [ for infinite time until there were updates in the handle-path ] # result gets 0 if the return was because of a change-event. (otherwise it is an exception or some other error) result = win32event.WaitForMultipleObjects( stop_handles, 0, win32event.INFINITE ) # -> (handles, wait for one(0) / wait for all(1), event for one - infinte time) if result == win32con.WAIT_OBJECT_0: # ( if result == 0 ) 0 is the first handle in the [] # after = os.listdir(path) after = walk(path) added = [f for f in after if not f in before] if len(added) != 0: print "Added: ", ", ".join(added)
_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) extended_info['BasicLimitInformation'][ 'LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE win32job.SetInformationJobObject( hJob, win32job.JobObjectExtendedLimitInformation, extended_info) win32job.AssignProcessToJobObject(hJob, hProcess)
def gotoxy(x,y) : class COORD(Structure) : _fields_ = [("X",c_short) , ("Y" ,c_short)] windll.kernel32.SetConsoleCursorPosition(win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE), (COORD(x,y)))
def CreateProcessWithLogonW(lpUsername=None, lpDomain=None, lpPassword=None, dwLogonFlags=0, lpApplicationName=None, lpCommandLine=None, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None): if not lpUsername: lpUsername = NULL else: lpUsername = ctypes.c_wchar_p(lpUsername) if not lpDomain: lpDomain = NULL else: lpDomain = ctypes.c_wchar_p(lpDomain) if not lpPassword: lpPassword = NULL else: lpPassword = ctypes.c_wchar_p(lpPassword) if not lpApplicationName: lpApplicationName = NULL else: lpApplicationName = ctypes.c_wchar_p(lpApplicationName) if not lpCommandLine: lpCommandLine = NULL else: lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine) if not lpEnvironment: lpEnvironment = NULL else: lpEnvironment = ctypes.c_wchar_p(lpEnvironment) if not lpCurrentDirectory: lpCurrentDirectory = NULL else: lpCurrentDirectory = ctypes.c_wchar_p(lpCurrentDirectory) if not lpStartupInfo: lpStartupInfo = STARTUPINFO() lpStartupInfo.cb = ctypes.sizeof(STARTUPINFO) lpStartupInfo.lpReserved = 0 lpStartupInfo.lpDesktop = 0 lpStartupInfo.lpTitle = 0 lpStartupInfo.dwFlags = 0 lpStartupInfo.cbReserved2 = 0 lpStartupInfo.lpReserved2 = 0 lpStartupInfo.hStdInput = win32api.GetStdHandle( win32api.STD_INPUT_HANDLE) lpStartupInfo.hStdOutput = win32api.GetStdHandle( win32api.STD_OUTPUT_HANDLE) lpStartupInfo.hStdError = win32api.GetStdHandle( win32api.STD_ERROR_HANDLE) lpProcessInformation = PROCESS_INFORMATION() lpProcessInformation.hProcess = INVALID_HANDLE_VALUE lpProcessInformation.hThread = INVALID_HANDLE_VALUE lpProcessInformation.dwProcessId = 0 lpProcessInformation.dwThreadId = 0 dwCreationFlags |= win32process.CREATE_NEW_CONSOLE success = ctypes.windll.advapi32.CreateProcessWithLogonW( lpUsername, lpDomain, lpPassword, dwLogonFlags, lpApplicationName, ctypes.byref(lpCommandLine), dwCreationFlags, lpEnvironment, lpCurrentDirectory, ctypes.byref(lpStartupInfo), ctypes.byref(lpProcessInformation)) if success == FALSE: raise ctypes.WinError() win32event.WaitForSingleObject(lpProcessInformation.hProcess, win32event.INFINITE) ctypes.windll.kernel32.CloseHandle(lpProcessInformation.hProcess) ctypes.windll.kernel32.CloseHandle(lpProcessInformation.hThread) return lpProcessInformation