logs the output from a remote command
  the input should be an open channel in  the case of synchronous better_exec_command
  otherwise this will not log anything and simply return to the caller
  :param chan:
  :return:
160424
def log_output(chan):
  
  if hasattr(chan, "recv"):
    str = chan.recv(1024)
    msgs = []
    while len(str) > 0:
      msgs.append(str)
      str = chan.recv(1024)
    msg = ''.join(msgs).strip()
    if len(msg) > 0:
      logger.info(msg)
853813
def execute_cmd(cmd, **kwargs):
    
    yield '$ {}\n'.format(' '.join(cmd))
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.STDOUT

    proc = subprocess.Popen(cmd, **kwargs)

    # Capture output for logging.
    # Each line will be yielded as text.
    # This should behave the same as .readline(), but splits on `\r` OR `\n`,
    # not just `\n`.
    buf = []
    def flush():
        line = b''.join(buf).decode('utf8', 'replace')
        buf[:] = []
        return line

    c_last = ''
    try:
        for c in iter(partial(proc.stdout.read, 1), b''):
            if c_last == b'\r' and buf and c != b'\n':
                yield flush()
            buf.append(c)
            if c == b'\n':
                yield flush()
            c_last = c
    finally:
        ret = proc.wait()
        if ret != 0:
            raise subprocess.CalledProcessError(ret, cmd)
591907
def runCommandReturnOutput(cmd):
    
    splits = shlex.split(cmd)
    proc = subprocess.Popen(
        splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise subprocess.CalledProcessError(stdout, stderr)
    return stdout, stderr
93994
def getOutput(self, command, env={}, path=None,
                  uid=None, gid=None, usePTY=0, childFDs=None):
        
        deferred = defer.Deferred()
        processProtocol = _SummaryProcessProtocol(deferred)
        self.execute(processProtocol, command, env,
                     path, uid, gid, usePTY, childFDs)
        @deferred.addCallback
        def getStdOut(tuple_):
            stdout, _stderr, _returnCode = tuple_
            return stdout
        return deferred
353698
def call_ext_prog(self, prog, timeout=300, stderr=True,
                      chroot=True, runat=None):
        
        return self.get_command_output(prog, timeout=timeout, stderr=stderr,
                                       chroot=chroot, runat=runat)
205969
def cmd(send, msg, args):
    
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('channel', nargs='+', action=arguments.ChanParser)
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    for chan in cmdargs.channels:
        args['handler'].do_part(chan, args['nick'], args['target'], args['type'], send, args['handler'].connection)
1140647
def _exec(cmd):
        
        process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

        # pylint: disable=unexpected-keyword-arg
        (stdout, stderr) = process.communicate(timeout=defaults.DEFAULT_VCS_TIMEOUT)

        return process.returncode, stdout.decode(), stderr.decode()
288748
def log_and_clear_command_output(command, stream)
      output = command.public_send(stream)
      log_command_data(command, stream, output)
      command.public_send("#{stream}=", "")
    end
664267
def _exec_command(self, cmd):
        
        _, out, err = self._client.exec_command(cmd, timeout=self._timeout)
        return out.read().strip() if not err.read().strip() else None
963197
def execute_command(self, command, **kwargs):
        

        self.info_log("executing command: %s" % command)

        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            username = kwargs.get(
                'username',
                self.browser_config.get('username')
            )
            password = self.browser_config.get('password')

            ssh.connect(self.get_ip(), username=username, password=password)

            stdin, stdout, stderr = ssh.exec_command(command)

            ssh.close()

            return (stdout, stderr)

        except Exception as e:
            msg = "Execute_command exception: %s" % str(e)
            self.error_log(msg)
            raise Exception(msg)
1098525
def redirect_output!
      if log_path = options[:log_path]
        # if the log directory doesn't exist, create it
        FileUtils.mkdir_p File.dirname(options[:log_path]), :mode => 0755
        # touch the log file to create it
        FileUtils.touch log_path
        # Set permissions on the log file
        File.chmod(0644, log_path)
        # Reopen $stdout (NOT +STDOUT+) to start writing to the log file
        $stdout.reopen(log_path, 'a')
        # Redirect $stderr to $stdout
        $stderr.reopen $stdout
        $stdout.sync = true
      else # redirect to /dev/null
        # We're not bothering to sync if we're dumping to /dev/null
        # because /dev/null doesn't care about buffered output
        $stdin.reopen '/dev/null'
        $stdout.reopen '/dev/null', 'a'
        $stderr.reopen $stdout
      end
      log_path = options[:log_path] ? options[:log_path] : '/dev/null'
    end
455821
def _check_output(self, command):
        """"""
        try:
            if sys.version_info[0] > 2:
                return check_output(self.base_command + command, stderr=STDOUT).decode('utf8')
            else:
                return check_output(self.base_command + command, stderr=STDOUT)
        except CalledProcessError as command_error:
            raise GitCommandException(*command_error.args)
1056493
def captureOutput(func, *args, **kwargs):
    
    stdout = sys.stdout
    sys.stdout = StringIO.StringIO()
    stderr = sys.stderr
    sys.stderr = StringIO.StringIO()
    try:
        func(*args, **kwargs)
        stdoutOutput = sys.stdout.getvalue()
        stderrOutput = sys.stderr.getvalue()
    finally:
        sys.stdout.close()
        sys.stdout = stdout
        sys.stderr.close()
        sys.stderr = stderr
    return stdoutOutput, stderrOutput
576413
def logs(channel):
	""
	default_url = 'http://' + socket.getfqdn()
	base = pmxbot.config.get('logs URL', default_url)
	logged_channel = channel in pmxbot.config.log_channels
	path = '/channel/' + channel.lstrip('#') if logged_channel else '/'
	return urllib.parse.urljoin(base, path)
491020
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
        '''  '''

        bufsize = 4096
        try:
            chan = self.ssh.get_transport().open_session()
        except Exception, e:
            msg = "Failed to open session"
            if len(str(e)) > 0:
                msg += ": %s" % str(e)
            raise errors.AnsibleConnectionFailed(msg)
        chan.get_pty()

        if not self.runner.sudo or not sudoable:
            if executable:
                quoted_command = executable + ' -c ' + pipes.quote(cmd)
            else:
                quoted_command = cmd
            vvv("EXEC %s" % quoted_command, host=self.host)
            chan.exec_command(quoted_command)
        else:
            shcmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            vvv("EXEC %s" % shcmd, host=self.host)
            sudo_output = ''
            try:
                chan.exec_command(shcmd)
                if self.runner.sudo_pass:
                    while not sudo_output.endswith(prompt):
                        chunk = chan.recv(bufsize)
                        if not chunk:
                            if 'unknown user' in sudo_output:
                                raise errors.AnsibleError(
                                    'user %s does not exist' % sudo_user)
                            else:
                                raise errors.AnsibleError('ssh connection ' +
                                    'closed waiting for password prompt')
                        sudo_output += chunk
                    chan.sendall(self.runner.sudo_pass + '\n')
            except socket.timeout:
                raise errors.AnsibleError('ssh timed out waiting for sudo.\n' + sudo_output)

        stdout = ''.join(chan.makefile('rb', bufsize))
        stderr = ''.join(chan.makefile_stderr('rb', bufsize))
        return (chan.recv_exit_status(), '', stdout, stderr)
28958
def get_simple_output(self, stderr=STDOUT):
        
        args = shlex.split(self.cmd)
        proc = Popen(args, stdout=PIPE, stderr=stderr)
        return proc.communicate()[0].decode("utf8")
1034382
protected function sshExec($remote_host, $command, &$output, &$return, $hide_pattern = '', $hide_replacement = '', $ouput_loglevel = LOG_INFO)
	{
		$cmd = $this->ssh_path .' -p '. $this->remote_port .' '. $this->remote_user .'@'. $remote_host .' "'. str_replace('"', '\"', $command) .'"';

		if ($hide_pattern != '') {
			$show_cmd = preg_replace($hide_pattern, $hide_replacement, $cmd);
		} else {
			$show_cmd = $cmd;
		}

		$this->log('sshExec: '. $show_cmd, $ouput_loglevel);

		exec($cmd, $output, $return);
	}