Exemple #1
0
        def _execute_child(self, args, executable, preexec_fn, close_fds,
                           cwd, env, universal_newlines,
                           startupinfo, creationflags,
                           p2cread, p2cwrite,
                           c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (MS Windows version)"""

            # Process startup details
            if startupinfo == None:
                startupinfo = STARTUPINFO()
            if not None in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= STARTF_USESTDHANDLES 
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            # Start the process
            try:
                hp, ht, pid, tid = CreateProcess(executable, args,
                                                 None, None,  # No special security
                                                 1,           # Must inherit handles to pass std handles
                                                 creationflags,
                                                 env,
                                                 cwd,
                                                 startupinfo)
            except pywintypes.error, e:
                # Translate pywintypes.error to WindowsError, which is
                # a subclass of OSError. FIXME: We should really
                # translate errno using _sys_errlist (or simliar), but
                # how can this be done from Python?
                raise WindowsError(*e.args)
Exemple #2
0
def run(argv=None):
    if argv is None:
        argv = sys.argv
    args = []
    exists = os.path.exists
    # munge unix-y path-like args into windows-y path-like args
    for a in argv[1:]:
        if exists(a):
            kept = a
        else:
            # delay the call to cygpath until here, where it's necessary
            _a = cygpath(a)
            # _a may be an existing or new file (new if containing dir exists)
            e = os.path.exists
            if exists(_a) or os.path.isdir(os.path.dirname(_a)):
                kept = _a
            else:
                kept = a
        if ' ' in kept or '\r' in kept or '\n' in kept:
            kept = '"%s"' % (kept,)
        args.append(kept)

    # read from stdin, which is sometimes useful
    si = STARTUPINFO() # I hate boilerplate crap
    si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
    si.dwFlags = win32process.STARTF_USESTDHANDLES


    # clobber $SHELL, which breaks ! commands when set to something Cygwin-y
    os.environ['SHELL'] = os.environ['COMSPEC']
    CreateProcess(None, 
                  r'%s %s' % (which("gvim_.exe")[0], ' '.join(args)),
                  None, None, 1,
                  win32con.CREATE_NO_WINDOW, None, None, si)
    return 1
Exemple #3
0
        def _execute_child(self, args, executable, preexec_fn, close_fds, cwd,
                           env, universal_newlines, startupinfo, creationflags,
                           p2cread, p2cwrite, c2pread, c2pwrite, errread,
                           errwrite):
            """Execute program (MS Windows version)"""

            # Process startup details
            if startupinfo == None:
                startupinfo = STARTUPINFO()
            if not None in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= STARTF_USESTDHANDLES
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            # Start the process
            try:
                hp, ht, pid, tid = CreateProcess(
                    executable,
                    args,
                    None,
                    None,  # No special security
                    1,  # Must inherit handles to pass std handles
                    creationflags,
                    env,
                    cwd,
                    startupinfo)
            except pywintypes.error, e:
                # Translate pywintypes.error to WindowsError, which is
                # a subclass of OSError. FIXME: We should really
                # translate errno using _sys_errlist (or simliar), but
                # how can this be done from Python?
                raise WindowsError(*e.args)
Exemple #4
0
 def __create_process(self, command):
     """
     Opens a new process
     """
     try:
         startup_info = STARTUPINFO()
         startup_info.dwFlags = STARTF_USESHOWWINDOW
         startup_info.wShowWindow = SW_NORMAL
         CreateProcess(None, command, None, None, 0, NORMAL_PRIORITY_CLASS, None, None, startup_info)
         result = "Opened " + command
     except:
         result = "ERROR: internal error"
     return result
Exemple #5
0
 def run_program(entry, path, parent):  # noqa
     import re
     cmdline = entry_to_cmdline(entry, path)
     flags = win32con.CREATE_DEFAULT_ERROR_MODE | win32con.CREATE_NEW_PROCESS_GROUP
     if re.match(r'"[^"]+?(.bat|.cmd|.com)"', cmdline, flags=re.I):
         flags |= win32con.CREATE_NO_WINDOW
         console = ' (console)'
     else:
         flags |= win32con.DETACHED_PROCESS
         console = ''
     print('Running Open With commandline%s:' % console,
           repr(entry['cmdline']), ' |==> ', repr(cmdline))
     try:
         with sanitize_env_vars():
             process_handle, thread_handle, process_id, thread_id = CreateProcess(
                 None, cmdline, None, None, False, flags, None, None,
                 STARTUPINFO())
         WaitForInputIdle(process_handle, 2000)
     except Exception as err:
         return error_dialog(
             parent,
             _('Failed to run'),
             _('Failed to run program, click "Show Details" for more information'
               ),
             det_msg='Command line: %r\n%s' % (cmdline, as_unicode(err)))
Exemple #6
0
 def __init__(self, command):
     """Launch editor process"""
     try:
         self.handle, nil, nil, nil = CreateProcess(
             None, command, None, None, 1, 0, None, None, STARTUPINFO())
     except pywintypes.error, e:
         fatalError('Error launching editor process\n'
                    '(%s):\n%s' % (command, e[2]))
Exemple #7
0
def main():
    """Get data from all of the runs and make a graph for each variable's average."""
    vals = [file for file in os.listdir('.') if 'val' in file]
    run_graphs = {}
    avg_graphs = {}
    for val in vals:
        with open(val, 'r') as f:
            run = val.replace('val', '').replace('.txt', '')
            data = parse_val(f.read())
            run_graphs[run] = data

    for run, graph in run_graphs.items():
        for k, v in graph['k'].items():
            construct_graph(x=graph['x'],
                            y=v,
                            title=cfg.run_title_format,
                            fname=cfg.run_fname_format,
                            RUN=run,
                            KEY=k)

            if len(v) < avg_graphs.setdefault(k, {}).setdefault(
                    'length', cfg.duration):
                avg_graphs[k]['length'] = len(v)
            avg_graphs[k].setdefault('x', []).append(graph['x'])
            avg_graphs[k].setdefault('y', []).append(v)

    for k, graph in avg_graphs.items():
        avgs_x = [
            sum(li) // len(li) for li in [[r[n] for r in graph['x']]
                                          for n in range(graph['length'])]
        ]
        avgs_y = [
            sum(li) // len(li) for li in [[r[n] for r in graph['y']]
                                          for n in range(graph['length'])]
        ]
        construct_graph(avgs_x,
                        avgs_y,
                        cfg.avg_title_format,
                        cfg.avg_fname_format,
                        KEY=k)

        if cfg.avg_tables:
            lines = '\n'.join([
                cfg.avg_table_data_format.replace('X',
                                                  str(x)).replace('Y', str(y))
                for x, y in zip(avgs_x, avgs_y)
            ])
            with open(
                    cfg.avg_table_fname_format.replace('KEY', k) + '.txt',
                    'w') as f:
                f.write(lines)

    if cfg.remove_non_statistics:
        os.system(f'del {cfg.entity_image} {cfg.food_image} {cfg.exe}')

    if cfg.enable_spreadsheet:
        CreateProcess(None, 'spreadsheet.exe', None, None, False, 0, None,
                      None, STARTUPINFO())
    def _execute_child(self, args, executable, preexec_fn, close_fds,
                           cwd, env, universal_newlines,
                           startupinfo, creationflags, shell,
                           p2cread, p2cwrite,
                           c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (MS Windows version)"""

            if not isinstance(args, types.StringTypes):
                args = list2cmdline(args)

            # Process startup details
            if startupinfo is None:
                startupinfo = STARTUPINFO()
            if None not in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= STARTF_USESTDHANDLES
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            if shell:
                startupinfo.dwFlags |= STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = SW_HIDE
                comspec = os.environ.get("COMSPEC", "cmd.exe")
                args = comspec + " /c " + args
                if (GetVersion() >= 0x80000000L or
                        os.path.basename(comspec).lower() == "command.com"):
                    # Win9x, or using command.com on NT. We need to
                    # use the w9xpopen intermediate program. For more
                    # information, see KB Q150956
                    # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
                    w9xpopen = self._find_w9xpopen()
                    args = '"%s" %s' % (w9xpopen, args)
                    # Not passing CREATE_NEW_CONSOLE has been known to
                    # cause random failures on win9x.  Specifically a
                    # dialog: "Your program accessed mem currently in
                    # use at xxx" and a hopeful warning about the
                    # stability of your system.  Cost is Ctrl+C wont
                    # kill children.
                    creationflags |= CREATE_NEW_CONSOLE
Exemple #9
0
    def runOdis(self):
        '''
                运行Odis Webservice
        '''
        # WebserviceCommand1='de.volkswagen.odis.vaudas.vehiclefunction.automation.webservice.enabled=True'
        # WebserviceCommand2='de.volkswagen.odis.vaudas.vehiclefunction.automation.webservice.port='+ WebservicePort

        print("... initializing ODISInf")
        sErrorMessage = ''
        self.sInstDir = self.__getInstDir()
        print("... checking ODIS process")
        if not self.__procExist():
            print("... ODIS websevice process not found, starting new")
            print("... checking registry for ODIS home")
            if self.sInstDir != None:
                sCommand = path.join(self.sInstDir, "OffboardDiagLauncher.exe")
                # sConfigfile = path.join(self.sInstDir, "\configuration\config.ini")
                # print("... ODIS path: %s", sCommand)
                # print("... Config path: %s", sConfigfile)
            else:
                sErrorMessage = 'no ODIS installation found'
                print('no ODIS installation found')
                return sErrorMessage

            sCommandAttribute = '-configuration configuration\\webservice.ini'
            print("... executing command: %s %s" %
                  (sCommand, sCommandAttribute))
            sCommandAttribute = '"' + sCommand + '"' + ' ' + sCommandAttribute
            hProcess, hThread, processId, threadId = CreateProcess(
                sCommand, sCommandAttribute, None, None, 0, 0, None, None,
                STARTUPINFO())
            Sleep(30000)
            print 'ODIS started...', hProcess, hThread, processId, threadId
            i = 0
            while True:
                try:
                    client = Client('http://localhost:' + WebservicePort +
                                    '/OdisAutomationService?wsdl')
                    client.set_options(timeout=3600)
                    self.aService = client.service
                    break
                except URLError:
                    if i < 20:
                        print(
                            'failed to establish the ODIS webservice connection, try again in 10s'
                        )
                        i += 1
                        Sleep(5000)
                    else:
                        sErrorMessage = 'failed to connect to ODIS webservice'
                        print(sErrorMessage)
                        return sErrorMessage
Exemple #10
0
def main():
    """Run the simulation."""
    current = strftime(cfg.dir_format)
    mkdir(current)

    for to_copy in listdir('bundle'):
        try:
            copy2(path.join('bundle', to_copy), current)
        except SameFileError:
            pass

    for run in range(1, cfg.runs + 1):
        CreateProcess(None, f'{path.join(current, cfg.exe)} {run}', None, None,
                      False, 0, None, current, STARTUPINFO())
        due = time() + cfg.duration
        while True:
            if time() > due:
                system(f'TASKKILL /F /IM {cfg.exe}')
                break
            sleep(1)

    CreateProcess(None, path.join(current, "graph.exe"), None, None, False, 0,
                  None, current, STARTUPINFO())
Exemple #11
0
 def run_program(entry, path, parent):  # noqa
     cmdline = entry_to_cmdline(entry, path)
     print('Running Open With commandline:', repr(entry['cmdline']), ' |==> ', repr(cmdline))
     try:
         with sanitize_env_vars():
             process_handle, thread_handle, process_id, thread_id = CreateProcess(
                 None, cmdline, None, None, False, win32con.CREATE_DEFAULT_ERROR_MODE | win32con.CREATE_NEW_PROCESS_GROUP | win32con.DETACHED_PROCESS,
                 None, None, STARTUPINFO())
         WaitForInputIdle(process_handle, 2000)
     except Exception as err:
         return error_dialog(
             parent, _('Failed to run'), _(
             'Failed to run program, click "Show Details" for more information'),
             det_msg='Command line: %r\n%s' %(cmdline, as_unicode(err)))
Exemple #12
0
 def StartYardServer(self):
     try:
         rkey = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Webers\\Y.A.R.D")
         path = RegQueryValueEx(rkey, "program")[0]
         if not os.path.exists(path):
             raise Exception
     except:
         raise self.Exception(
             "Please start Yards.exe first and configure it.")
     try:
         hProcess = CreateProcess(None, path, None, None, 0,
                                  CREATE_NEW_CONSOLE, None, None,
                                  STARTUPINFO())[0]
     except Exception, exc:
         raise eg.Exception(FormatError(exc[0]))
Exemple #13
0
def _stub(cmd_name, stdin_name, stdout_name, stderr_name):
    """INTERNAL: Stub process that will start up the child process."""
    # Open the 4 pipes (command, stdin, stdout, stderr)
    cmd_pipe = CreateFile(cmd_name, GENERIC_READ|GENERIC_WRITE, 0, None,
                          OPEN_EXISTING, 0, None)
    SetHandleInformation(cmd_pipe, HANDLE_FLAG_INHERIT, 1)
    stdin_pipe = CreateFile(stdin_name, GENERIC_READ, 0, None,
                            OPEN_EXISTING, 0, None)
    SetHandleInformation(stdin_pipe, HANDLE_FLAG_INHERIT, 1)
    stdout_pipe = CreateFile(stdout_name, GENERIC_WRITE, 0, None,
                             OPEN_EXISTING, 0, None)
    SetHandleInformation(stdout_pipe, HANDLE_FLAG_INHERIT, 1)
    stderr_pipe = CreateFile(stderr_name, GENERIC_WRITE, 0, None,
                             OPEN_EXISTING, 0, None)
    SetHandleInformation(stderr_pipe, HANDLE_FLAG_INHERIT, 1)

    # Learn what we need to do..
    header = _read_header(cmd_pipe)
    input = _parse_header(header)
    if 'command' not in input or 'args' not in input:
        ExitProcess(2)

    # http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx
    startupinfo = STARTUPINFO()
    startupinfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
    startupinfo.hStdInput = stdin_pipe
    startupinfo.hStdOutput = stdout_pipe
    startupinfo.hStdError = stderr_pipe
    startupinfo.wShowWindow = SW_HIDE

    # Grant access so that our parent can open its grandchild.
    if 'parent_sid' in input:
        mysid = _get_current_sid()
        parent = ConvertStringSidToSid(input['parent_sid'])
        sattrs = _create_security_attributes(mysid, parent,
                                             access=PROCESS_ALL_ACCESS)
    else:
        sattrs = None

    try:
        res = CreateProcess(input['command'], input['args'], sattrs, None,
                            True, CREATE_NEW_CONSOLE, os.environ, os.getcwd(),
                            startupinfo)
    except WindowsError as e:
        message = _quote_header(str(e))
        WriteFile(cmd_pipe, 'status=error\nmessage=%s\n\n' % message)
        ExitProcess(3)
    else:
        pid = res[2]

    # Pass back results and exit
    err, nbytes = WriteFile(cmd_pipe, 'status=ok\npid=%s\n\n' % pid)
    ExitProcess(0)
Exemple #14
0
        def detach(cls):
            script = sys.argv[0]
            sys.argv.append('--detached')
            if special in sys.argv:
                sys.argv.remove(special)
                return 0  #we're in the child just return

            #we're in the parent do stuff
            try:
                from subprocess import CreateProcess

                class STARTUPINFO:
                    dwFlags = 0
                    hStdInput = None
                    hStdOutput = None
                    hStdError = None

                class pywintypes:
                    error = IOError
            except ImportError:
                try:
                    from win32process import CreateProcess, STARTUPINFO
                except ImportError:
                    return 1, "Can't import CreateProcess from subprocess or win32process"
            exe = sys.executable.replace('n.exe', 'nw.exe')
            startupinfo = STARTUPINFO()
            args = ''.join([' "%s"' % a for a in sys.argv[1:]])
            cmd = '"%s" "%s"%s %s' % (exe, script, args, special)
            try:
                hp, ht, pid, tid = CreateProcess(
                    None,
                    cmd,
                    # no special security
                    None,
                    None,
                    0,  #don't inherit standard handles
                    0x208,
                    None,
                    None,
                    startupinfo)
            except pywintypes.error, e:
                return 2, str(e)
Exemple #15
0
    def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env,
                       universal_newlines, startupinfo, creationflags, shell,
                       p2cread, p2cwrite, c2pread, c2pwrite, errread,
                       errwrite):
        """Execute program (MS Windows version)"""

        if not isinstance(args, types.StringTypes):
            args = list2cmdline(args)

        # Process startup details
        if startupinfo is None:
            startupinfo = STARTUPINFO()
        if None not in (p2cread, c2pwrite, errwrite):
            startupinfo.dwFlags |= STARTF_USESTDHANDLES
            startupinfo.hStdInput = p2cread
            startupinfo.hStdOutput = c2pwrite
            startupinfo.hStdError = errwrite

        if shell:
            startupinfo.dwFlags |= STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = SW_HIDE
            comspec = os.environ.get("COMSPEC", "cmd.exe")
            args = comspec + " /c " + args
            if (GetVersion() >= 0x80000000L
                    or os.path.basename(comspec).lower() == "command.com"):
                # Win9x, or using command.com on NT. We need to
                # use the w9xpopen intermediate program. For more
                # information, see KB Q150956
                # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
                w9xpopen = self._find_w9xpopen()
                args = '"%s" %s' % (w9xpopen, args)
                # Not passing CREATE_NEW_CONSOLE has been known to
                # cause random failures on win9x.  Specifically a
                # dialog: "Your program accessed mem currently in
                # use at xxx" and a hopeful warning about the
                # stability of your system.  Cost is Ctrl+C wont
                # kill children.
                creationflags |= CREATE_NEW_CONSOLE
Exemple #16
0
        def _execute_child(self, args, executable, preexec_fn, close_fds, cwd,
                           env, universal_newlines, startupinfo, creationflags,
                           shell, p2cread, p2cwrite, c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (MS Windows version)"""

            if not isinstance(args, str):
                args = list2cmdline(args)

            # Process startup details
            default_startupinfo = STARTUPINFO()
            if startupinfo == None:
                startupinfo = default_startupinfo
            if not None in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= STARTF_USESTDHANDLES
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            if shell:
                default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
                default_startupinfo.wShowWindow = SW_HIDE
                comspec = os.environ.get("COMSPEC", "cmd.exe")
                args = comspec + " /c " + args
                if (GetVersion() >= 0x80000000
                        or os.path.basename(comspec).lower() == "command.com"):
                    # Win9x, or using command.com on NT. We need to
                    # use the w9xpopen intermediate program. For more
                    # information, see KB Q150956
                    # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
                    w9xpopen = self._find_w9xpopen()
                    args = '"%s" %s' % (w9xpopen, args)
                    # Not passing CREATE_NEW_CONSOLE has been known to
                    # cause random failures on win9x.  Specifically a
                    # dialog: "Your program accessed mem currently in
                    # use at xxx" and a hopeful warning about the
                    # stability of your system.  Cost is Ctrl+C wont
                    # kill children.
                    creationflags |= CREATE_NEW_CONSOLE

            # Start the process
            try:
                hp, ht, pid, tid = CreateProcess(
                    executable,
                    args,
                    # no special security
                    None,
                    None,
                    # must inherit handles to pass std
                    # handles
                    1,
                    creationflags,
                    env,
                    cwd,
                    startupinfo)
            except pywintypes.error as e:
                # Translate pywintypes.error to WindowsError, which is
                # a subclass of OSError.  FIXME: We should really
                # translate errno using _sys_errlist (or simliar), but
                # how can this be done from Python?
                raise WindowsError(*e.args)

            # Retain the process handle, but close the thread handle
            self._handle = hp
            self.pid = pid
            ht.Close()

            # 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 != None:
                p2cread.Close()
            if c2pwrite != None:
                c2pwrite.Close()
            if errwrite != None:
                errwrite.Close()
Exemple #17
0
    def initTester(self, dConfig):
        log.debug("... initializing ODISInf")
        sErrorMessage = ''
        self.sInstDir = self.__getInstDir()
        log.debug("... checking ODIS process")      
        if not self.__procExist():
            log.debug("... ODIS websevice process not found, starting new")
            
            log.debug("... checking registry for ODIS home")
                            

            if self.sInstDir != None:
                sCommand = path.join(self.sInstDir, "OffboardDiagLauncher.exe")
            else:
                sErrorMessage = 'no ODIS installation found'
                return sErrorMessage

            sCommandAttribute = '-configuration configuration\\webservice.ini'
            log.debug("... executing command: %s %s", sCommand, sCommandAttribute)
            sCommandAttribute = '"' + sCommand + '"' + ' ' + sCommandAttribute
            hProcess, hThread, processId, threadId = CreateProcess(sCommand, sCommandAttribute, None, None, 0, 0, None, None, STARTUPINFO())
            Sleep(60000)
        
        i = 0
        while True:
            try:
                client = Client('http://localhost:8081/OdisAutomationService?wsdl')
                client.set_options(timeout=3600)
                self.aService = client.service
                
                break
            except URLError:
                if i < 20:
                    log.debug('failed to establish the ODIS webservice connection, try again in 10s')
                    i += 1
                    Sleep(5000)
                else:
                    sErrorMessage = 'failed to connect to ODIS webservice'
                    log.error(sErrorMessage)
                    return sErrorMessage
        
        log.debug('... set vehicle project to "%s"', dConfig['sVehicleProject'])
        try:
            self.aTraceState=client.factory.create('traceSTATE')           
            self.aService.setVehicleProject(dConfig['sVehicleProject'])
            sErrorMessage = self.switchECU(dConfig)
            if(sErrorMessage != ''):
                self.deInitTester()
            self.__backupOldProtocolAndTraceFiles()
        except WebFault, e:
            sErrorMessage = self.__encodeStr(e.fault.faultstring)
            log.error(sErrorMessage)
Exemple #18
0
    def _spawn(self, command, args=None):
        """Start the child process. If args is empty, command will be parsed
        according to the rules of the MS C runtime, and args will be set to
        the parsed args."""
        if args:
            args = args[:]  # copy
            args.insert(0, command)
        else:
            args = split_command_line(command)
            command = args[0]

        self.command = command
        self.args = args
        command = which(self.command)
        if command is None:
            raise ExceptionPexpect('Command not found: %s' % self.command)
        args = join_command_line(self.args)

        # Create the pipes
        sids = [_get_current_sid()]
        if self.username and self.password:
            sids.append(_lookup_sid(self.domain, self.username))
        cmd_pipe, cmd_name = _create_named_pipe(self.pipe_template, sids)
        stdin_pipe, stdin_name = _create_named_pipe(self.pipe_template, sids)
        stdout_pipe, stdout_name = _create_named_pipe(self.pipe_template, sids)
        stderr_pipe, stderr_name = _create_named_pipe(self.pipe_template, sids)

        startupinfo = STARTUPINFO()
        startupinfo.dwFlags |= STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_HIDE

        python = os.path.join(sys.exec_prefix, 'python.exe')
        pycmd = 'import winpexpect; winpexpect._stub(r"%s", r"%s", r"%s", r"%s")' \
                    % (cmd_name, stdin_name, stdout_name, stderr_name)
        pyargs = join_command_line([python, '-c', pycmd])

        # Create a new token or run as the current process.
        if self.username and self.password:
            token = LogonUser(self.username, self.domain, self.password,
                              LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT)
            res = CreateProcessAsUser(token, python, pyargs, None, None,
                                      False, CREATE_NEW_CONSOLE, self.env,
                                      self.cwd, startupinfo)
        else:
            token = None
            res = CreateProcess(python, pyargs, None, None, False,
                                CREATE_NEW_CONSOLE, self.env, self.cwd,
                                startupinfo)
        child_handle = res[0]
        res[1].Close()  # don't need thread handle

        ConnectNamedPipe(cmd_pipe)
        ConnectNamedPipe(stdin_pipe)
        ConnectNamedPipe(stdout_pipe)
        ConnectNamedPipe(stderr_pipe)

        # Tell the stub what to do and wait for it to exit
        WriteFile(cmd_pipe, 'command=%s\n' % command)
        WriteFile(cmd_pipe, 'args=%s\n' % args)
        if token:
            parent_sid = ConvertSidToStringSid(_get_current_sid())
            WriteFile(cmd_pipe, 'parent_sid=%s\n' % str(parent_sid))
        WriteFile(cmd_pipe, '\n')

        header = _read_header(cmd_pipe)
        output = _parse_header(header)
        if output['status'] != 'ok':
            m = 'Child did not start up correctly. '
            m += output.get('message', '')
            raise ExceptionPexpect(m)
        self.pid = int(output['pid'])
        self.child_handle = OpenProcess(PROCESS_ALL_ACCESS, False, self.pid)
        WaitForSingleObject(child_handle, INFINITE)

        # Start up the I/O threads
        self.child_fd = open_osfhandle(stdin_pipe.Detach(), 0)  # for pexpect
        self.stdout_handle = stdout_pipe
        self.stdout_reader = Thread(target=self._child_reader,
                                    args=(self.stdout_handle,))
        self.stdout_reader.start()
        self.stderr_handle = stderr_pipe
        self.stderr_reader = Thread(target=self._child_reader,
                                    args=(self.stderr_handle,))
        self.stderr_reader.start()
        self.terminated = False
        self.closed = False
Exemple #19
0
def _call_command(command,
                  logoutput=False,
                  cwd=None,
                  env=None,
                  wait_for_finish=True,
                  timeout=None,
                  user=None):
    # TODO implement timeout, wait_for_finish
    Logger.info("Executing %s" % (command))
    if user:
        domain, username = UserHelper.parse_user_name(user, ".")

        proc_token = OpenProcessToken(GetCurrentProcess(),
                                      TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES)

        old_states = []

        privileges = [
            SE_ASSIGNPRIMARYTOKEN_NAME,
            SE_INCREASE_QUOTA_NAME,
        ]

        for priv in privileges:
            old_states.append(QueryPrivilegeState(proc_token, priv))
            AdjustPrivilege(proc_token, priv)
            QueryPrivilegeState(proc_token, priv)

        user_token = LogonUser(username, domain, Script.get_password(user),
                               win32con.LOGON32_LOGON_SERVICE,
                               win32con.LOGON32_PROVIDER_DEFAULT)
        env_token = DuplicateTokenEx(user_token, SecurityIdentification,
                                     TOKEN_QUERY, TokenPrimary)
        # getting updated environment for impersonated user and merge it with custom env
        current_env = CreateEnvironmentBlock(env_token, False)
        current_env = _merge_env(current_env, env)

        si = STARTUPINFO()
        out_handle, err_handle, out_file, err_file = _create_tmp_files(
            current_env)
        ok, si.hStdInput = _safe_duplicate_handle(
            GetStdHandle(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")

        Logger.debug("Redirecting stdout to '{0}', stderr to '{1}'".format(
            out_file.name, err_file.name))

        si.dwFlags = win32con.STARTF_USESTDHANDLES
        si.lpDesktop = ""

        try:
            info = CreateProcessAsUser(user_token, None, command, None, None,
                                       1, win32con.CREATE_NO_WINDOW,
                                       current_env, cwd, si)
            hProcess, hThread, dwProcessId, dwThreadId = info
            hThread.Close()

            try:
                WaitForSingleObject(hProcess, INFINITE)
            except KeyboardInterrupt:
                pass
            out, err = _get_files_output(out_file, err_file)
            code = GetExitCodeProcess(hProcess)
        finally:
            for priv in privileges:
                old_state = old_states.pop(0)
                AdjustPrivilege(proc_token, priv, old_state)
    else:
        # getting updated environment for current process and merge it with custom env
        cur_token = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY)
        current_env = CreateEnvironmentBlock(cur_token, False)
        current_env = _merge_env(current_env, env)
        proc = subprocess.Popen(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT,
                                cwd=cwd,
                                env=current_env,
                                shell=False)
        out, err = proc.communicate()
        code = proc.returncode

    if logoutput and out:
        Logger.info(out)
    if logoutput and err:
        Logger.info(err)
    return code, out, err
def _call_command(command, logoutput=False, cwd=None, env=None, wait_for_finish=True, timeout=None, user=None):
  # TODO implement timeout, wait_for_finish
  Logger.info("Executing %s" % (command))
  if user:
    domain, username = UserHelper.parse_user_name(user, ".")

    proc_token = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES)

    old_states = []

    privileges = [
      SE_ASSIGNPRIMARYTOKEN_NAME,
      SE_INCREASE_QUOTA_NAME,
    ]

    for priv in privileges:
      old_states.append(QueryPrivilegeState(proc_token, priv))
      AdjustPrivilege(proc_token, priv)
      QueryPrivilegeState(proc_token, priv)

    user_token = LogonUser(username, domain, Script.get_password(user), win32con.LOGON32_LOGON_SERVICE,
                           win32con.LOGON32_PROVIDER_DEFAULT)
    env_token = DuplicateTokenEx(user_token, SecurityIdentification, TOKEN_QUERY, TokenPrimary)
    # getting updated environment for impersonated user and merge it with custom env
    current_env = CreateEnvironmentBlock(env_token, False)
    current_env = _merge_env(current_env, env)

    si = STARTUPINFO()
    out_handle, err_handle, out_file, err_file = _create_tmp_files(current_env)
    ok, si.hStdInput = _safe_duplicate_handle(GetStdHandle(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")

    Logger.debug("Redirecting stdout to '{0}', stderr to '{1}'".format(out_file.name, err_file.name))

    si.dwFlags = win32con.STARTF_USESTDHANDLES
    si.lpDesktop = ""

    try:
      info = CreateProcessAsUser(user_token, None, command, None, None, 1, win32con.CREATE_NO_WINDOW, current_env, cwd, si)
      hProcess, hThread, dwProcessId, dwThreadId = info
      hThread.Close()

      try:
        WaitForSingleObject(hProcess, INFINITE)
      except KeyboardInterrupt:
        pass
      out, err = _get_files_output(out_file, err_file)
      code = GetExitCodeProcess(hProcess)
    finally:
      for priv in privileges:
        old_state = old_states.pop(0)
        AdjustPrivilege(proc_token, priv, old_state)
  else:
    # getting updated environment for current process and merge it with custom env
    cur_token = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY)
    current_env = CreateEnvironmentBlock(cur_token, False)
    current_env = _merge_env(current_env, env)
    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            cwd=cwd, env=current_env, shell=False)
    out, err = proc.communicate()
    code = proc.returncode

  if logoutput and out:
    Logger.info(out)
  if logoutput and err:
    Logger.info(err)
  return code, out, err
        def _execute_child(self, args, executable, preexec_fn, close_fds,
                           cwd, env, universal_newlines,
                           startupinfo, creationflags, shell,
                           p2cread, p2cwrite,
                           c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (MS Windows version)"""

            if not isinstance(args, str):
                args = list2cmdline(args)

            # Process startup details
            if startupinfo is None:
                startupinfo = STARTUPINFO()
            if None not in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= STARTF_USESTDHANDLES
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            if shell:
                startupinfo.dwFlags |= STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = SW_HIDE
                comspec = os.environ.get("COMSPEC", "cmd.exe")
                args = comspec + " /c " + args
                if (GetVersion() >= 0x80000000 or
                        os.path.basename(comspec).lower() == "command.com"):
                    # Win9x, or using command.com on NT. We need to
                    # use the w9xpopen intermediate program. For more
                    # information, see KB Q150956
                    # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
                    w9xpopen = self._find_w9xpopen()
                    args = '"%s" %s' % (w9xpopen, args)
                    # Not passing CREATE_NEW_CONSOLE has been known to
                    # cause random failures on win9x.  Specifically a
                    # dialog: "Your program accessed mem currently in
                    # use at xxx" and a hopeful warning about the
                    # stability of your system.  Cost is Ctrl+C wont
                    # kill children.
                    creationflags |= CREATE_NEW_CONSOLE

            # Start the process
            try:
                hp, ht, pid, tid = CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         int(not close_fds),
                                         creationflags,
                                         env,
                                         cwd,
                                         startupinfo)
            except pywintypes.error as e:
                # Translate pywintypes.error to WindowsError, which is
                # a subclass of OSError.  FIXME: We should really
                # translate errno using _sys_errlist (or simliar), but
                # how can this be done from Python?
                raise WindowsError(*e.args)

            # Retain the process handle, but close the thread handle
            self._child_created = True
            self._handle = hp
            self.pid = pid
            ht.Close()

            # 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 is not None:
                p2cread.Close()
            if c2pwrite is not None:
                c2pwrite.Close()
            if errwrite is not None:
                errwrite.Close()