Run a shim command.

        If tty is enabled, we must scp the shim to the target system and
        execute it there
160974
def shim_cmd(self, cmd_str, extension='py'):
        '''
        
        '''
        if not self.tty and not self.winrm:
            return self.shell.exec_cmd(cmd_str)

        # Write the shim to a temporary file in the default temp directory
        with tempfile.NamedTemporaryFile(mode='w+b',
                                         prefix='shim_',
                                         delete=False) as shim_tmp_file:
            shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))

        # Copy shim to target system, under $HOME/.<randomized name>
        target_shim_file = '.{0}.{1}'.format(
            binascii.hexlify(os.urandom(6)).decode('ascii'),
            extension
        )
        if self.winrm:
            target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
        self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)

        # Remove our shim file
        try:
            os.remove(shim_tmp_file.name)
        except IOError:
            pass

        # Execute shim
        if extension == 'ps1':
            ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
        else:
            if not self.winrm:
                ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
            else:
                ret = saltwinshell.call_python(self, target_shim_file)

        # Remove shim from target system
        if not self.winrm:
            self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
        else:
            self.shell.exec_cmd('del {0}'.format(target_shim_file))

        return ret
296690
def run(self):
        
        with self._scp_bensh_runner():
            self._execute_bensh_runner()
            path = self._retrieve_tarball()
            try:
                self._aggregate_tarball(path)
            finally:
                os.remove(path)
900574
def _run_tty(self, writer, reader):
        """"""
        # allow window-change signal to reflow screen
        signal.signal(signal.SIGWINCH, self.on_resize)

        page_idx = page_offset = 0
        while True:
            if self.dirty:
                page_idx, page_offset = self.draw(writer,
                                                  page_idx,
                                                  page_offset)
                self.dirty = self.STATE_CLEAN
            inp = reader(timeout=0.25)
            if inp is not None:
                nxt, noff = self.process_keystroke(inp,
                                                   page_idx,
                                                   page_offset)
            if not self.dirty:
                self.dirty = nxt != page_idx or noff != page_offset
            page_idx, page_offset = nxt, noff
            if page_idx == -1:
                return
1278570
def run(
    commands,
    shell=None,
    prompt_template="default",
    speed=1,
    quiet=False,
    test_mode=False,
    commentecho=False,
):
    """"""
    if not quiet:
        secho("We'll do it live!", fg="red", bold=True)
        secho(
            "STARTING SESSION: Press Ctrl-C at any time to exit.",
            fg="yellow",
            bold=True,
        )
        click.pause()

    click.clear()
    state = SessionState(
        shell=shell,
        prompt_template=prompt_template,
        speed=speed,
        test_mode=test_mode,
        commentecho=commentecho,
    )

    i = 0
    while i < len(commands):
        command = commands[i].strip()
        i += 1
        if not command:
            continue
        is_comment = command.startswith("#")
        if not is_comment:
            command_as_list = shlex.split(ensure_utf8(command))
        else:
            command_as_list = None
        shell_match = SHELL_RE.match(command)
        if is_comment:
            # Parse comment magic
            match = OPTION_RE.match(command)
            if match:
                option, arg = match.group("option"), match.group("arg")
                func = OPTION_MAP[option]
                func(state, arg)
            elif state.commentecho():
                comment = command.lstrip("#")
                secho(comment, fg="yellow", bold=True)
            continue
        # Handle 'export' and 'alias' commands by storing them in SessionState
        elif command_as_list and command_as_list[0] in ["alias", "export"]:
            magictype(
                command, prompt_template=state["prompt_template"], speed=state["speed"]
            )
            # Store the raw commands instead of using add_envvar and add_alias
            # to avoid having to parse the command ourselves
            state.add_command(command)
        # Handle ```python and ```ipython by running "player" consoles
        elif shell_match:
            shell_name = shell_match.groups()[0].strip()
            py_commands = []
            more = True
            while more:  # slurp up all the python code
                try:
                    py_command = commands[i].rstrip()
                except IndexError:
                    raise SessionError(
                        "Unmatched {0} code block in "
                        "session file.".format(shell_name)
                    )
                i += 1
                if py_command.startswith("```"):
                    i += 1
                    more = False
                else:
                    py_commands.append(py_command)
            # Run the player console
            magictype(
                shell_name,
                prompt_template=state["prompt_template"],
                speed=state["speed"],
            )

            if shell_name == "ipython":
                try:
                    from doitlive.ipython_consoles import start_ipython_player
                except ImportError:
                    raise RuntimeError(
                        "```ipython blocks require IPython to be installed"
                    )
                # dedent all the commands to account for IPython's autoindentation
                ipy_commands = [textwrap.dedent(cmd) for cmd in py_commands]
                start_ipython_player(ipy_commands, speed=state["speed"])
            else:
                start_python_player(py_commands, speed=state["speed"])
        else:
            # goto_stealthmode determines when to switch to stealthmode
            goto_stealthmode = magicrun(command, **state)
            # stealthmode allows user to type live commands outside of automated script
            i -= stealthmode(state, goto_stealthmode)
    echo_prompt(state["prompt_template"])
    wait_for(RETURNS)
    if not quiet:
        secho("FINISHED SESSION", fg="yellow", bold=True)
844948
def run(args: List[str],
        get_output: bool = False,
        encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]:
    
    printable = " ".join(shlex.quote(x) for x in args).replace("\n", r"\n")
    log.debug("Running external command: {}", printable)
    if get_output:
        p = subprocess.run(args, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE, check=True)
        stdout, stderr = p.stdout.decode(encoding), p.stderr.decode(encoding)
    else:
        subprocess.check_call(args)
        stdout, stderr = "", ""
    return stdout, stderr
413109
def run_subprocess(command):
    
    x = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
    out, err = x.communicate()
    out = out.decode('utf-8')
    err = err.decode('utf-8')
    return out, err
409316
def run(command, **kw):
    """"""
    # Windows low-level subprocess API wants str for current working
    # directory.
    if sys.platform == 'win32':
        _cwd = kw.get('cwd', None)
        if _cwd is not None:
            kw['cwd'] = _cwd.decode()
    try:
        # In Python 3, iterating over bytes yield integers, so we call
        # `splitlines()` to force Python 3 to give us lines instead.
        return check_output(command, **kw).splitlines()
    except CalledProcessError:
        return ()
    except FileNotFoundError:
        print("The {} binary was not found. Skipping directory {}.\n"
              .format(command[0], kw['cwd'].decode("UTF-8")))
        return ()
730759
def runCommand(command, silent=False, shell=False):
    
    splits = shlex.split(command)
    runCommandSplits(splits, silent=silent, shell=shell)
876731
def run_module_command(cmd_list, env_vars, exit_on_error=True):
    """"""
    if exit_on_error:
        try:
            subprocess.check_call(cmd_list, env=env_vars)
        except subprocess.CalledProcessError as shelloutexc:
            sys.exit(shelloutexc.returncode)
    else:
        subprocess.check_call(cmd_list, env=env_vars)
458805
def exec_command(self, cmd, tmp_path, sudo_user,sudoable=False, executable='/bin/sh'):
        '''  '''

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-tt", "-q"] + self.common_args + [self.host]

        if not self.runner.sudo or not sudoable:
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)
        else:
            sudocmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            ssh_cmd.append(sudocmd)

        vvv("EXEC %s" % ssh_cmd, host=self.host)
        try:
            # Make sure stdin is a proper (pseudo) pty to avoid: tcgetattr errors
            import pty
            master, slave = pty.openpty()
            p = subprocess.Popen(ssh_cmd, stdin=slave,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = os.fdopen(master, 'w', 0)
        except:
            p = subprocess.Popen(ssh_cmd, stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = p.stdin

        self._send_password()

        if self.runner.sudo and sudoable and self.runner.sudo_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            sudo_output = ''
            while not sudo_output.endswith(prompt):
                rfd, wfd, efd = select.select([p.stdout], [],
                                              [p.stdout], self.runner.timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                    if not chunk:
                        raise errors.AnsibleError('ssh connection closed waiting for sudo password prompt')
                    sudo_output += chunk
                else:
                    stdout = p.communicate()
                    raise errors.AnsibleError('ssh connection error waiting for sudo password prompt')
            stdin.write(self.runner.sudo_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        # We can't use p.communicate here because the ControlMaster may have stdout open as well
        stdout = ''
        stderr = ''
        while True:
            rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout, p.stderr], 1)
            if p.stdout in rfd:
                dat = os.read(p.stdout.fileno(), 9000)
                stdout += dat
                if dat == '':
                    p.wait()
                    break
            elif p.stderr in rfd:
                dat = os.read(p.stderr.fileno(), 9000)
                stderr += dat
                if dat == '':
                    p.wait()
                    break
            elif p.poll() is not None:
                break
        stdin.close() # close stdin after we read from stdout (see also issue #848)

        if p.returncode != 0 and stderr.find('Bad configuration option: ControlPersist') != -1:
            raise errors.AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ansible_ssh_args in the config file) before running again')

        return (p.returncode, '', stdout, stderr)
653580
def setup(addr, user, remote_path, local_key=None):
    """"""
    port = find_port(addr, user)

    if not port or not is_alive(addr, user):
        port = new_port()

        scp(addr, user, __file__, '~/unixpipe', local_key)

        ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,
                    '-o', 'ExitOnForwardFailure=yes',
                    '-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,
                    '-o', 'ControlMaster=auto',
                    '%s@%s' % (user, addr,), 'python', '~/unixpipe',
                    'server', remote_path]
        if local_key:
            ssh_call.insert(1, local_key)
            ssh_call.insert(1, '-i')

        subprocess.call(ssh_call)
        # XXX Sleep is a bad way to wait for the tunnel endpoint
        time.sleep(1)

    return port
1256289
def _cmd_str(self, cmd, ssh='ssh'):
        '''
        
        '''

        # TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will
        # need to deliver the SHIM to the remote host and execute it there

        command = [ssh]
        if ssh != 'scp':
            command.append(self.host)
        if self.tty and ssh == 'ssh':
            command.append('-t -t')
        if self.passwd or self.priv:
            command.append(self.priv and self._key_opts() or self._passwd_opts())
        if ssh != 'scp' and self.remote_port_forwards:
            command.append(' '.join(['-R {0}'.format(item)
                                      for item in self.remote_port_forwards.split(',')]))
        if self.ssh_options:
            command.append(self._ssh_opts())

        command.append(cmd)

        return ' '.join(command)
478316
def run
      raise("Already running a pry-remote session!") if
        PryByebug.current_remote_server

      PryByebug.current_remote_server = self

      setup
      Pry.start @object, input: client.input_proxy, output: client.output
    end
1244525
def run(*args)
      stdin = nil
      cmd = SysCmd.command name do
        args.each do |arg|
          case arg
          when Hash
            arg.each do |key, value|
              next if value.nil?
              case value
              when Array
                value = value*","
              when String
                if value.include?("\n")
                  raise "Cannot pass multiple options through STDIN" if stdin
                  stdin = Support.unindent(value)
                  value = "-"
                  input stdin
                end
              end
              option key.to_s, equal_value: value
            end
          else
            option arg
          end
        end
      end
      if @context
        @context.execute cmd
      end
      cmd
    end
1370369
def _RunCommand(self, command):
    """"""
    arguments = shlex.split(command)
    process = subprocess.Popen(
        arguments, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
        universal_newlines=True)
    if not process:
      raise RuntimeError("Running: {0:s} failed.".format(command))

    output, error = process.communicate()
    if process.returncode != 0:
      error = "\n".join(error.split("\n")[-5:])
      raise RuntimeError("Running: {0:s} failed with error:\n{1:s}.".format(
          command, error))

    return output
1252463
def run(self, command):
        
        if isinstance(command, basestring):
            command = command.split()
        else:
            command = list(command)
        self.external.omero_cli(command)
1288524
def run_fsm(self, name, command, events, transitions, timeout, max_transitions=20):
        """"""
        self.ctrl.send_command(command)
        return FSM(name, self, events, transitions, timeout=timeout, max_transitions=max_transitions).run()