Beispiel #1
0
    def stop(self, pid):
        # call the method that any subclasses out there may implement:
        self.onStop()

        winver = sys.getwindowsversion()
        # This is unfortunately needed because runzope.exe is a setuptools
        # generated .exe that spawns off a sub process, so pid would give us
        # the wrong event name.
        child_pid = int(
            open(self.getReg('pid_filename', keyname='PythonClass')).read())

        # Stop the child process by sending signals to the special named event.
        # We give it 90 seconds to shutdown normally. If that doesn't stop
        # things, we give it 30 seconds to do a "fast" shutdown.
        for sig, timeout in (
            (signal.SIGINT, 30),
            (signal.SIGTERM, 10)):
            # See the Signals.WinSignalHandler module for
            # the source of this event name
            event_name = "Zope-%d-%d" % (child_pid, sig)
            if winver[0] >= 5 and winver[3] == 2:
                event_name = "Global\\" + event_name
            try:
                he = win32event.OpenEvent(win32event.EVENT_MODIFY_STATE, 0,
                                          event_name)
            except win32event.error:
                # no other expected error - report it.
                self.warning("Failed to open child shutdown event %s"
                             % (event_name, ))
                continue

            win32event.SetEvent(he)
            # It should be shutting down now - wait for termination, reporting
            # progress as we go.
            for i in range(timeout):
                # wait for one second
                rc = win32event.WaitForSingleObject(self.hZope, 1000)
                if rc == win32event.WAIT_OBJECT_0:
                    break
            # Process terminated - no need to try harder.
            if rc == win32event.WAIT_OBJECT_0:
                break

        if win32process.GetExitCodeProcess(self.hZope)==win32con.STILL_ACTIVE:
            # None of the signals worked, so kill the process
            self.warning(
                "Terminating process as it could not be gracefully ended")
            win32api.TerminateProcess(self.hZope, 3)

        output = self.getCapturedOutput()
        if output:
            self.info("Process terminated with output:\n"+output)
Beispiel #2
0
 def terminate(self):
     '''
     Terminates the process
     '''
     try:
         win32api.TerminateProcess(self._handle, 1)
     except OSError:
         # ERROR_ACCESS_DENIED (winerror 5) is received when the
         # process already died.
         ecode = win32process.GetExitCodeProcess(self._handle)
         if ecode == win32con.STILL_ACTIVE:
             raise
         self.exitstatus = ecode
Beispiel #3
0
def runAsAdmin(cmdLine=None, wait=True):

    if os.name != 'nt':
        # raise RuntimeError, "This function is only implemented on Windows."
        raise Exception("RuntimeError",
                        "This function is only implemented on Windows.")

    # import win32api, win32con, win32event, win32process
    import win32con, win32event, win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon

    python_exe = sys.executable

    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType, types.ListType):
        # raise ValueError, "cmdLine is not a sequence."
        raise Exception("ValueError", "cmdLine is not a sequence.")
    cmd = '"%s"' % (cmdLine[0], )
    # XXX TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x, ) for x in cmdLine[1:]])
    # cmdDir = ''
    showCmd = win32con.SW_SHOWNORMAL
    # showCmd = win32con.SW_HIDE
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']
        # obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        # print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = None

    return rc
Beispiel #4
0
    def start(self):
        """
        Starts the process and the logger pipes for its stdout and
        stderr.
        """

        creation_flags = 0
        if sys.platform == "win32" and _JOB_OBJECT is not None:
            creation_flags |= win32process.CREATE_BREAKAWAY_FROM_JOB

        # Use unbuffered I/O pipes to avoid adding delay between when the subprocess writes output
        # and when the LoggerPipe thread reads it.
        buffer_size = 0

        # Close file descriptors in the child process before executing the program. This prevents
        # file descriptors that were inherited due to multiple calls to fork() -- either within one
        # thread, or concurrently from multiple threads -- from causing another subprocess to wait
        # for the completion of the newly spawned child process. Closing other file descriptors
        # isn't supported on Windows when stdout and stderr are redirected.
        close_fds = (sys.platform != "win32")

        with _POPEN_LOCK:
            self._process = subprocess.Popen(self.args,
                                             bufsize=buffer_size,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.PIPE,
                                             close_fds=close_fds,
                                             env=self.env,
                                             creationflags=creation_flags)
            self.pid = self._process.pid

        self._stdout_pipe = pipe.LoggerPipe(self.logger, logging.INFO,
                                            self._process.stdout)
        self._stderr_pipe = pipe.LoggerPipe(self.logger, logging.ERROR,
                                            self._process.stderr)

        self._stdout_pipe.wait_until_started()
        self._stderr_pipe.wait_until_started()

        if sys.platform == "win32" and _JOB_OBJECT is not None:
            try:
                win32job.AssignProcessToJobObject(_JOB_OBJECT,
                                                  self._process._handle)
            except win32job.error as err:
                # ERROR_ACCESS_DENIED (winerror=5) is received when the process has already died.
                if err.winerror != winerror.ERROR_ACCESS_DENIED:
                    raise
                return_code = win32process.GetExitCodeProcess(
                    self._process._handle)
                if return_code == win32con.STILL_ACTIVE:
                    raise
Beispiel #5
0
def RunAsAdmin(conn=None, cmdLine=None, showCmd=False, wait=True):

    if os.name != 'nt':
        raise (RuntimeError, "This function is only implemented on Windows.")

    if cmdLine is None:
        python_exe = sys.executable
        cmdLine = [python_exe] + sys.argv
    else:
        try:
            #check if list/tuple
            ",".join(cmdLine)
            print(cmdLine[0])
        except:
            raise Exception(TypeError, cmdLine,
                            "cmdLine is not a list or a tuple type")

    cmd = cmdLine[0]
    params = " ".join([x for x in cmdLine[1:]])

    #show shell or keep it hidden
    if showCmd is True:
        showCmd = win32con.SW_SHOWNORMAL
    elif showCmd is False:
        showCmd = win32con.SW_HIDE
    else:
        raise Exception(ArgError, "showCmd: Invalid value - ", showCmd)

    lpVerb = 'runas'  # causes UAC elevation prompt.
    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    # cmd+= " " +params
    # procHandle, threadHandle, procId, threadId = DoCreateProcess(cmd)
    if conn:
        pass
        conn.put("")

    if wait:
        procHandle = procInfo['hProcess']
        # print        ("pr",prponerocHandle
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        print("Process handle %s returned code %s" % (procHandle, rc))
    else:
        rc = None
    return rc
Beispiel #6
0
def run_as_admin(file, params):
    #SEE_MASK_NO_CONSOLE = 0x00008000
    SEE_MASK_NOCLOSEPROCESS = 0x00000040
    SHOWNORMAL = 1
    procInfo = shell.ShellExecuteEx(lpVerb='runas',
                                    lpFile=file,
                                    lpParameters=params,
                                    nShow=SHOWNORMAL,
                                    fMask=SEE_MASK_NOCLOSEPROCESS)
    procHandle = procInfo['hProcess']
    obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
    rc = win32process.GetExitCodeProcess(procHandle)
    print "Process handle %s returned code %s" % (procHandle, rc)
    return rc
Beispiel #7
0
    def start(self):
        """Start the process and the logger pipes for its stdout and stderr."""

        creation_flags = 0
        if sys.platform == "win32" and _JOB_OBJECT is not None:
            creation_flags |= win32process.CREATE_BREAKAWAY_FROM_JOB

        # Tests fail if a process takes too long to startup and listen to a socket. Use buffered
        # I/O pipes to give the process some leeway.
        buffer_size = 1024 * 1024

        # Close file descriptors in the child process before executing the program. This prevents
        # file descriptors that were inherited due to multiple calls to fork() -- either within one
        # thread, or concurrently from multiple threads -- from causing another subprocess to wait
        # for the completion of the newly spawned child process. Closing other file descriptors
        # isn't supported on Windows when stdout and stderr are redirected.
        close_fds = (sys.platform != "win32")

        with _POPEN_LOCK:
            self._process = subprocess.Popen(
                self.args, bufsize=buffer_size, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                close_fds=close_fds, env=self.env, creationflags=creation_flags, cwd=self._cwd)
            self.pid = self._process.pid

            # TODO: check path exists
            if _config.UNDO_RECORDER_PATH is not None and ("mongod" in self.args[0]
                                                           or "mongos" in self.args[0]):
                recorder_args = [
                    _config.UNDO_RECORDER_PATH, "--thread-fuzzing", "-p",
                    str(self.pid)
                ]
                self._recorder = subprocess.Popen(recorder_args, bufsize=buffer_size, env=self.env,
                                                  creationflags=creation_flags)

        self._stdout_pipe = pipe.LoggerPipe(self.logger, logging.INFO, self._process.stdout)
        self._stderr_pipe = pipe.LoggerPipe(self.logger, logging.ERROR, self._process.stderr)

        self._stdout_pipe.wait_until_started()
        self._stderr_pipe.wait_until_started()

        if sys.platform == "win32" and _JOB_OBJECT is not None:
            try:
                win32job.AssignProcessToJobObject(_JOB_OBJECT, self._process._handle)
            except win32job.error as err:
                # ERROR_ACCESS_DENIED (winerror=5) is received when the process has already died.
                if err.winerror != winerror.ERROR_ACCESS_DENIED:
                    raise
                return_code = win32process.GetExitCodeProcess(self._process._handle)
                if return_code == win32con.STILL_ACTIVE:
                    raise
Beispiel #8
0
    def Wait(self) -> int:
        """Waits for the process to exit.

    Returns:
      The exit code.

    Raises:
      Error: on system error.
    """
        res = win32event.WaitForSingleObject(self._handle, win32event.INFINITE)
        if res == win32event.WAIT_FAILED:
            raise Error("WaitForSingleObject failed.")
        exit_code = win32process.GetExitCodeProcess(self._handle)
        self._exit_stack.close()
        return exit_code
Beispiel #9
0
 def _kill(self):
     """
     Wrapper for os.kill to emulate kill if not on unix.
     """
     if sys.platform in ("win32"):
         import win32process
         if self._handle.handle > 0 and win32process.GetExitCodeProcess(self._handle) > 1:
             import win32api
             win32api.TerminateProcess(self._handle, 0)
         self._handle.Close()
         self._pid = None
     else:
         import signal
         os.kill(self._pid, signal.SIGTERM)
         self._pid = None
Beispiel #10
0
def runAsAdmin(cmd_line=None, wait=True, console=True):
    # TODO: complete description
    """
    Elevates a new python console window to Administrator.
    1- cmd_line: 
    2- wait    : 
    3- cmd     : Sets whether the python console should show it's window. It shows the window by default.
               : True          = shows the elevated python console window.
               : False or None = does not show the elevated python console window.
    """
    if os.name != 'nt':
        raise RuntimeError("This function is only implemented on Windows.\n")

    python_exe = sys.executable

    if cmd_line is None:
        cmd_line = [python_exe] + sys.argv  # cmd_line = [cmd, params]
    elif type(cmd_line) not in (types.TupleType, types.ListType):
        raise ValueError("cmd_line is not a sequence.\n")

    cmd = '"%s"' % (cmd_line[0], )  # The path of the cmd window

    # TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x, ) for x in cmd_line[1:]
                       ])  # The path of the python script that called
    if console is False:
        show_cmd = win32con.SW_HIDE
    else:
        show_cmd = win32con.SW_SHOWNORMAL

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle of the process, so we can't get anything
    # useful from it. Therefore the more complex ShellExecuteEx() must be used.
    # NOTE: lpVerb='runas' causes UAC elevation prompt.
    procInfo = ShellExecuteEx(nShow=show_cmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb='runas',
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']
        obj = win32event.WaitForSingleObject(
            procHandle, win32event.INFINITE)  # TODO: Necessary?
        rc = win32process.GetExitCodeProcess(procHandle)
    else:
        rc = None

    return rc
Beispiel #11
0
def runAsAdmin(cmdLine=None, wait=True):
    """Attempt to relaunch the current script as an admin using the same
    command line parameters.  Pass cmdLine in to override and set a new
    command.  It must be a list of [command, arg1, arg2...] format.
    Set wait to False to avoid waiting for the sub-process to finish. You
    will not be able to fetch the exit code of the process if wait is
    False.
    Returns the sub-process return code, unless wait is False in which
    case it returns None.
    @WARNING: this function only works on Windows.
    """

    if os.name != 'nt':
        raise RuntimeError("This function is only implemented on Windows.")

    import win32con
    import win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon

    python_exe = sys.executable

    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType, types.ListType):
        raise ValueError("cmdLine is not a sequence.")
    cmd = '"%s"' % (cmdLine[0],)
    # XXX TODO: isn't there a function or something we can call to
    # massage command line params?
    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])

    showCmd = win32con.SW_SHOWNORMAL
    lpVerb = 'runas'  # causes UAC elevation prompt.

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']
        # obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
    else:
        rc = None

    return rc
Beispiel #12
0
def run_command_win32(cmd):
    sa = win32security.SECURITY_ATTRIBUTES()
    sa.bInheritHandle = True
    stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)

    si = win32process.STARTUPINFO()
    si.dwFlags = (win32process.STARTF_USESTDHANDLES
                  | win32process.STARTF_USESHOWWINDOW)
    si.wShowWindow = win32con.SW_HIDE
    si.hStdOutput = stdout_w

    process, thread, pid, tid = \
             win32process.CreateProcess(None, cmd, None, None, True,
                                        0, None, None, si)
    if process == None:
        return -1, ""

    # Must close the write handle in this process, or ReadFile will hang.
    stdout_w.Close()

    # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
    # which is okay because it happens when child process ends).
    data = ""
    error = 0
    while 1:
        try:
            hr, buffer = win32file.ReadFile(stdout_r, 4096)
            if hr != winerror.ERROR_IO_PENDING:
                data = data + buffer

        except pywintypes.error as e:
            if e.args[0] != winerror.ERROR_BROKEN_PIPE:
                error = 1
            break

    if error:
        return -2, ""

    # Everything is okay --- the called process has closed the pipe.
    # For safety, check that the process ended, then pick up its exit code.
    win32event.WaitForSingleObject(process, win32event.INFINITE)
    if win32process.GetExitCodeProcess(process):
        return -3, ""

    global debug
    if debug:
        sys.stdout.write(data)
    return 0, data
Beispiel #13
0
    def run_as(self, command):
        # Importing these only on windows, as they won't exist on linux.
        import win32api
        import win32event
        import win32process
        from winsys import _advapi32

        exit_code = -1
        process_handle = None
        thread_handle = None

        try:
            # Open process as that user
            # https://github.com/tjguk/winsys/blob/master/winsys/_advapi32.py
            proc_info = _advapi32.CreateProcessWithLogonW(
                username=self.username,
                domain=".",
                password=self.password,
                command_line=command)
            process_handle = proc_info.hProcess
            thread_handle = proc_info.hThread

            logger.debug("Waiting for process to finish. Timeout: {}ms".format(
                WAIT_TIMEOUT_IN_MILLISECONDS))

            # https://social.msdn.microsoft.com/Forums/vstudio/en-US/b6d6a7ae-71e9-4edb-ac8f
            # -408d2a41750d/what-events-on-a-process-handle-signal-satisify-waitforsingleobject
            # ?forum=vcgeneral
            # Ignoring return code, as we'll use `GetExitCode` to determine the state of the
            # process later.
            _ = win32event.WaitForSingleObject(
                # Waits until the specified object is signaled, or time-out.
                process_handle,  # Ping process handle
                WAIT_TIMEOUT_IN_MILLISECONDS,  # Timeout in milliseconds
            )

            exit_code = win32process.GetExitCodeProcess(process_handle)
        finally:
            try:
                if process_handle is not None:
                    win32api.CloseHandle(process_handle)
                if thread_handle is not None:
                    win32api.CloseHandle(thread_handle)
            except Exception as err:
                logger.error("Close handle error: " + str(err))

        return exit_code
Beispiel #14
0
 def is_process_active(pid):
     """
 @param  pid  long
 @return  bool
 """
     ret = False
     try:
         h = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False,
                                  pid)
         if h:
             status = win32process.GetExitCodeProcess(h)
             ret = status == win32con.STILL_ACTIVE
             win32api.CloseHandle(h)
     except:
         pass
     #except Exception, e: dwarn(e)
     return ret
Beispiel #15
0
def force_elevated():
	try:
		if sys.argv[-1] != 'asadmin':
			script = os.path.abspath(sys.argv[0])
			params = ' '.join(["\"%s\"" % script] + sys.argv[1:] + ['asadmin'])
			procInfo = shell.ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL,
								 fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
								 lpVerb='runas',
								 lpFile=sys.executable,
								 lpParameters=params)

			procHandle = procInfo['hProcess']    
			obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
			rc = win32process.GetExitCodeProcess(procHandle)

	except Exception as ex:
		print ex
    def install_pyside_windows(self, python_executable):
        """Install PySide2 python module to blender's python.

        Installation requires administration rights that's why it is required
        to use "pywin32" module which can execute command's and ask for
        administration rights.
        """
        try:
            import win32api
            import win32con
            import win32process
            import win32event
            import pywintypes
            from win32comext.shell.shell import ShellExecuteEx
            from win32comext.shell import shellcon
        except Exception:
            self.log.warning("Couldn't import \"pywin32\" modules")
            return

        try:
            # Parameters
            # - use "-m pip" as module pip to install PySide2 and argument
            #   "--ignore-installed" is to force install module to blender's
            #   site-packages and make sure it is binary compatible
            parameters = "-m pip install --ignore-installed PySide2"

            # Execute command and ask for administrator's rights
            process_info = ShellExecuteEx(
                nShow=win32con.SW_SHOWNORMAL,
                fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                lpVerb="runas",
                lpFile=python_executable,
                lpParameters=parameters,
                lpDirectory=os.path.dirname(python_executable))
            process_handle = process_info["hProcess"]
            obj = win32event.WaitForSingleObject(process_handle,
                                                 win32event.INFINITE)
            returncode = win32process.GetExitCodeProcess(process_handle)
            if returncode == 0:
                self.log.info(
                    "Successfully installed PySide2 module to blender.")
                return
        except pywintypes.error:
            pass

        self.log.warning("Failed to instal PySide2 module to blender.")
Beispiel #17
0
  def close(self):
    if self.file:
      self.file.close()
      self.file = None
      if sys.platform == "win32":
        win32event.WaitForMultipleObjects(self.wait_for, 1, win32event.INFINITE)
        return win32process.GetExitCodeProcess(self.child_pid)
      else:
        if self.thread:
          self.thread.join()
	if type(self.child_pid) == type([]):
          for pid in self.child_pid:
            exit = os.waitpid(pid, 0)[1]
          return exit
	else:
            return os.waitpid(self.child_pid, 0)[1]
    return None
def run_as_admin(*cmd_line, wait=True):
    verb = "runas"
    if not cmd_line:
        cmd_line = [sys.executable] + sys.argv
    cmd = cmd_line[0]
    params = " ".join(str(x) for x in cmd_line[1:])
    process_info = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL,
                                  fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                                  lpVerb=verb,
                                  lpFile=cmd,
                                  lpParameters=params)
    if wait:
        process_handle = process_info['hProcess']
        win32event.WaitForSingleObject(process_handle, win32event.INFINITE)
        return_code = win32process.GetExitCodeProcess(process_handle)
    else:
        return_code = None
    return return_code
Beispiel #19
0
        def call(self, method, args):
            """
            Launch program to consume file

            @type	method: string
            @param	method: Command to execute
            @type	args: array of objects
            @param	args: Arguments to pass
            """

            hProcess, hThread, dwProcessId, dwThreadId = win32process.CreateProcess(
                None, self.commandLine, None, None, 0,
                win32con.NORMAL_PRIORITY_CLASS, None, None, None)

            while win32process.GetExitCodeProcess(hProcess) == win32con.STILL_ACTIVE:
                time.sleep(0.25)

            self.closeApp(hProcess, self._windowName)
Beispiel #20
0
    def read_loop(self):

        while True:
            if not self.isalive(self.host_process):
                logger.info('Host process has been died.')
                return

            self.child_exitstatus = win32process.GetExitCodeProcess(
                self.__childProcess)
            if self.child_exitstatus != win32con.STILL_ACTIVE:
                logger.info(
                    f'Child finished with code: {self.child_exitstatus}')
                return

            consinfo = self.consout.GetConsoleScreenBufferInfo()
            cursorPos = consinfo['CursorPosition']

            if cursorPos.Y > maxconsoleY:
                '''If the console output becomes long, we suspend the child, read all output then
                clear the console before we resume the child.
                '''
                logger.info('cursorPos %s' % cursorPos)
                self.suspend_child()
                time.sleep(.2)
                self.send_to_host(self.readConsoleToCursor())
                self.refresh_console()
                self.resume_child()
            else:
                self.send_to_host(self.readConsoleToCursor())

            s = self.get_from_host()
            if s:
                logger.debug(f'get_from_host: {s}')
            else:
                logger.spam(f'get_from_host: {s}')
            if self.enable_signal_chars:
                for sig, char in SIGNAL_CHARS.items():
                    if char in s:
                        self.child_process.send_signal(sig)
            s = s.decode()
            self.write(s)

            time.sleep(.02)
Beispiel #21
0
    def run_vbox_installer_windows(cmd):
        cmd_dir = ''
        showCmd = win32con.SW_SHOWNORMAL
        lpVerb = 'runas'
        cmd = cmd.split(" ")
        installer = cmd[0]
        args = " ".join(cmd[1:])
        procInfo = ShellExecuteEx(nShow=showCmd,
                                  fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                                  lpVerb=lpVerb,
                                  lpFile=installer,
                                  lpParameters=args)

        procHandle = procInfo['hProcess']
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        # print "Process handle %s returned code %s" % (procHandle, rc)
        log.debug("Virtualbox setup finished")
        return rc
Beispiel #22
0
def ShutdownProcess(process_id, timeout, force=False):
    """Attempts to nicely close the specified process.

  Returns the exit code on success. Raises an error on failure.
  """

    # Open the process in question, so we can wait for it to exit.
    permissions = win32con.SYNCHRONIZE | win32con.PROCESS_QUERY_INFORMATION
    process_handle = win32api.OpenProcess(permissions, False, process_id)

    # Loop around to periodically retry to close Chrome.
    started = time.time()
    elapsed = 0
    while True:
        _LOGGER.debug('Shutting down process with PID=%d.', process_id)

        with open(os.devnull, 'w') as f:
            cmd = ['taskkill.exe', '/PID', str(process_id)]
            if force:
                cmd.append('/F')
            subprocess.call(cmd, shell=True, stdout=f, stderr=f)

        # Wait at most 2 seconds after each call to taskkill.
        curr_timeout_ms = int(max(2, timeout - elapsed) * 1000)

        _LOGGER.debug('Waiting for process with PID=%d to exit.', process_id)
        result = win32event.WaitForSingleObject(process_handle,
                                                curr_timeout_ms)
        # Exit the loop on successful wait.
        if result == win32event.WAIT_OBJECT_0:
            break

        elapsed = time.time() - started
        if elapsed > timeout:
            _LOGGER.debug('Timeout waiting for process to exit.')
            raise TimeoutException()

    exit_status = win32process.GetExitCodeProcess(process_handle)
    process_handle.Close()
    _LOGGER.debug('Process exited with status %d.', exit_status)

    return exit_status
def reqadminwin():
    import ctypes, win32com.shell.shell, win32event, win32process
    outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
    if ctypes.windll.shell32.IsUserAnAdmin():
        if os.path.isfile(outpath):
            sys.stderr = sys.stdout = open(outpath, 'w', 0)
        return
    with open(outpath, 'w+', 0) as outfile:
        hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
         lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
        while True:
            hr = win32event.WaitForSingleObject(hProc, 40)
            while True:
                line = outfile.readline()
                if not line: break
                sys.stdout.write(line)
            if hr != 0x102: break
    os.remove(outpath)
    sys.stderr = ''
    sys.exit(win32process.GetExitCodeProcess(hProc))
Beispiel #24
0
 def my_spawn(sh, escape, cmd, args, spawnenv):
     for var in spawnenv:
         spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
     sAttrs = win32security.SECURITY_ATTRIBUTES()
     StartupInfo = win32process.STARTUPINFO()
     newargs = ' '.join(map(escape, args[1:]))
     cmdline = cmd + " " + newargs
     # check for any special operating system commands
     if cmd == 'del':
         for arg in args[1:]:
             win32file.DeleteFile(arg)
         exit_code = 0
     else:
         # otherwise execute the command.
         hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
         win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
         exit_code = win32process.GetExitCodeProcess(hProcess)
         win32file.CloseHandle(hProcess);
         win32file.CloseHandle(hThread);
     return exit_code
Beispiel #25
0
 def process_exists(pid):
     try:
         if USE_PROCESS_QUERY_LIMITED_INFORMATION:
             #this one potentially works even for other user's processes
             h = win32api.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
         else:
             h = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, 0, pid)
     except pywintypes.error as e:
         if e.winerror == winerror.ERROR_INVALID_PARAMETER:
             #This error is returned if the pid doesn't match any known process
             return False
         elif e.winerror == winerror.ERROR_ACCESS_DENIED:
             raise AccessDeniedError(e)
         #Other errors are not expected
         raise
     try:
         exitcode = win32process.GetExitCodeProcess(h)
         return exitcode == win32con.STILL_ACTIVE
     finally:
         win32api.CloseHandle(h)
Beispiel #26
0
	def setExitStatus(self):
		"""Method to set the exit status of the process.
		
		"""
		with self.__lock:
			if self.exitStatus is not None: return self.exitStatus
			exitStatus = win32process.GetExitCodeProcess(self.__hProcess)
			if exitStatus != win32con.STILL_ACTIVE:
				try:
					if self.__hProcess: win32file.CloseHandle(self.__hProcess)
					if self.__hThread: win32file.CloseHandle(self.__hThread)
					if self.__stdin: win32file.CloseHandle(self.__stdin)
				except Exception as e:
					# these failed sometimes with 'handle is invalid', probably due to interference of stdin writer thread
					log.warning('Could not close process and thread handles for process %s: %s', self.pid, e)
				self.__stdin = self.__hThread = self.__hProcess = None
				self._outQueue = None
				self.exitStatus = exitStatus
			
			return self.exitStatus
Beispiel #27
0
    def eof(self):
        ### should be calling file.eof() here instead of file.close(), there
        ### may be data in the pipe or buffer after the process exits
        if sys.platform == "win32":
            r = win32event.WaitForMultipleObjects(self.wait_for, 1, 0)
            if r == win32event.WAIT_OBJECT_0:
                self.file.close()
                self.file = None
                return win32process.GetExitCodeProcess(self.child_pid)
            return None

        if self.thread and self.thread.isAlive():
            return None

        pid, status = os.waitpid(self.child_pid, os.WNOHANG)
        if pid:
            self.file.close()
            self.file = None
            return status
        return None
Beispiel #28
0
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
Beispiel #29
0
        def enumCallback(hwnd, windowName):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            try:

                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    return

                (threadId,
                 processId) = win32process.GetWindowThreadProcessId(hwnd)

                # Send WM_CLOSE message
                try:
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                    win32gui.PostQuitMessage(hwnd)
                except:
                    pass

                # Give it upto 5 sec
                for i in range(100):
                    if win32process.GetExitCodeProcess(
                            processId) != win32con.STILL_ACTIVE:
                        # Process exited already
                        return

                    time.sleep(0.25)

                try:
                    # Kill application
                    win32process.TerminateProcess(processId, 0)
                except:
                    pass
            except:
                pass
Beispiel #30
0
    def runAsAdmin(self, cmdLine=None, wait=True):
        """

        Executes the file again as admin.

        """
        python_exe = sys.executable
        cmdLine = [python_exe] + sys.argv
        cmd = '"%s"' % (cmdLine[0], )
        params = CHANGE_PASSWORD_FILE + self.password.text
        cmdDir = ''
        showCmd = win32con.SW_SHOWNORMAL
        lpVerb = 'runas'
        procInfo = ShellExecuteEx(nShow=showCmd,
                                  fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                                  lpVerb=lpVerb,
                                  lpFile=cmd,
                                  lpParameters=params)
        procHandle = procInfo['hProcess']
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)