Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
    command cmd returns the STDOUT of the command
961949
def _psrdp(cmd):
    '''
    
    '''
    rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '
           '-Namespace root\\CIMV2\\TerminalServices -Computer . '
           '-Authentication 6 -ErrorAction Stop')
    return __salt__['cmd.run']('{0} ; {1}'.format(rdp, cmd),
                               shell='powershell', python_shell=True)
659615
function Terminal(file, args, opt) {

  var self = this,
      env, cwd, name, cols, rows, term, agent, debug;

  // Backward compatibility.
  if (typeof args === 'string') {
    opt = {
      name: arguments[1],
      cols: arguments[2],
      rows: arguments[3],
      cwd: process.env.HOME
    };
    args = [];
  }

  // Arguments.
  args = args || [];
  file = file || 'cmd.exe';
  opt = opt || {};

  env = extend({}, opt.env);

  cols = opt.cols || 80;
  rows = opt.rows || 30;
  cwd = opt.cwd || process.cwd();
  name = opt.name || env.TERM || 'Windows Shell';
  debug = opt.debug || false;

  env.TERM = name;

  // Initialize environment variables.
  env = environ(env);

  // If the terminal is ready
  this.isReady = false;

  // Functions that need to run after `ready` event is emitted.
  this.deferreds = [];

  // Create new termal.
  this.agent = new Agent(file, args, env, cwd, cols, rows, debug);

  // The dummy socket is used so that we can defer everything
  // until its available.
  this.socket = this.agent.ptySocket;

  // The terminal socket when its available
  this.dataPipe = null;

  // Not available until `ready` event emitted.
  this.pid = this.agent.pid;
  this.fd = this.agent.fd;
  this.pty = this.agent.pty;

  // The forked windows terminal is not available
  // until `ready` event is emitted.
  this.socket.on('ready_datapipe', function (socket) {

    // Set terminal socket
    self.dataPipe = socket;

    // These events needs to be forwarded.
    ['connect', 'data', 'end', 'timeout', 'drain'].forEach(function(event) {
      self.dataPipe.on(event, function(data) {

        // Wait until the first data event is fired
        // then we can run deferreds.
        if(!self.isReady && event == 'data') {

          // Terminal is now ready and we can
          // avoid having to defer method calls.
          self.isReady = true;

          // Execute all deferred methods
          self.deferreds.forEach(function(fn) {
            // NB! In order to ensure that `this` has all
            // its references updated any variable that
            // need to be available in `this` before
            // the deferred is run has to be declared
            // above this forEach statement.
            fn.run();
          });

          // Reset
          self.deferreds = [];

        }

        // Emit to dummy socket
        self.socket.emit(event, data);

      });
    });

    // Resume socket.
    self.dataPipe.resume();

    // Shutdown if `error` event is emitted.
    self.dataPipe.on('error', function (err) {

      // Close terminal session.
      self._close();

      // EIO, happens when someone closes our child
      // process: the only process in the terminal.
      // node < 0.6.14: errno 5
      // node >= 0.6.14: read EIO
      if (err.code) {
        if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) return;
      }

      // Throw anything else.
      if (self.listeners('error').length < 2) {
        throw err;
      }

    });

    // Cleanup after the socket is closed.
    self.dataPipe.on('close', function () {
      Terminal.total--;
      self.emit('exit', null);
      self._close();
    });

  });

  this.file = file;
  this.name = name;
  this.cols = cols;
  this.rows = rows;

  this.readable = true;
  this.writable = true;

  Terminal.total++;
}
757421
def nice_execute(cmd)
      puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}")
      stdout, stderr, exit_status = Open3.capture3( cmd )
      unless stdout.empty?
        stdout.each_line do |line|
          print "** [out] #{line}"
          $stdout.flush
        end
      end
      unless stderr.empty?
        stderr.each_line do |line|
          $stderr.print red("** [err] #{line}")
          $stderr.flush
        end
      end
      exit_status
    end
1142590
def _run_cmd_get_output(cmd):
    
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    out, err = process.communicate()
    return out or err
1318714
def call(command, stdin=None, stdout=subprocess.PIPE, env=os.environ, cwd=None,
         shell=False, output_log_level=logging.INFO, sensitive_info=False):
    
    if not sensitive_info:
        logger.debug("calling command: %s" % command)
    else:
        logger.debug("calling command with sensitive information")
    try:
        args = command if shell else whitespace_smart_split(command)
        kw = {}
        if not shell and not which(args[0], cwd=cwd):
            raise CommandMissingException(args[0])
        if shell:
            kw['shell'] = True
        process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
                                   stderr=subprocess.STDOUT, env=env, cwd=cwd,
                                   **kw)
        output = process.communicate(input=stdin)[0]
        if output is not None:
            try:
                logger.log(output_log_level, output.decode('utf-8'))
            except UnicodeDecodeError:
                pass
        return (process.returncode, output)
    except OSError:
        e = sys.exc_info()[1]
        if not sensitive_info:
            logger.exception("Error running command: %s" % command)
            logger.error("Root directory: %s" % cwd)
            if stdin:
                logger.error("stdin: %s" % stdin)
        raise e
1052856
def execute(cmd, verbosityThreshold = 1, **kwargs):
    ''''''
    global exectue_defaults
    opts = merge(exectue_defaults, kwargs)              # the options computed from the default options together with the passed in options.
    subopts = filterKWArgsForFunc(opts, subprocess.Popen)
    formattedCmd = cmd.format(**getFormatBindings(cmd,1))

    shouldPrint = opts['verbosity'] >= verbosityThreshold
    isDryrun = opts['dryrun']

    if shouldPrint:
        msg = "would execute:" if isDryrun else "executing:"
        pre = "("+subopts['cwd']+")" if (subopts['cwd'] != exectue_defaults['cwd']) else ""
        print "{pre}{msg} {formattedCmd}".format(pre=pre, formattedCmd=formattedCmd, msg=msg)
    if isDryrun:
        return (0, None, None)

    printStdOut = shouldPrint and opts['permitShowingStdOut']
    printStdErr = shouldPrint and opts['permitShowingStdErr']
    returnCode = 0
    if opts['captureStdOutStdErr']:
        (returnCode, stdOut, stdErr) = _AsynchronouslyGetProcessOutput(formattedCmd, printStdOut, printStdErr, **subopts)    
    else:
        subopts['stdout'] = None if printStdOut else subprocess.PIPE
        subopts['stderr'] = None if printStdErr else subprocess.PIPE
        process = subprocess.Popen(formattedCmd, **subopts)
        res = process.communicate()
        returnCode = process.returncode
        stdOut = res[0]
        stdErr = res[1]

    if returnCode and not opts['ignoreErrors']:
        print colored('Command {} failed with return code {}!'.format(cmd, returnCode),'red')
        sys.exit(returnCode)
    
    # always print any errors
    return (returnCode, stdOut, stdErr)
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)
128087
def output_for(cmd, options = {})
      output = StringIO.new
      execute(cmd, options.merge(:outstream => output))
      output.string
    end
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()
400902
function start(cmd, { silent = false, env = null } = {}) {
    const parts = cmd.split(' ');
    const command = parts[0][0] === '.' ? path.resolve(parts[0]) : parts[0];
    const handle = {
        process: child_process_1.spawn(command, parts.slice(1), {
            stdio: silent ? 'pipe' : 'inherit',
            env: env || process.env,
            cwd: process.cwd()
        }),
        promise: Promise.resolve()
    };
    handle.promise = new Promise(function (resolve, reject) {
        let resolved = false;
        handle.process.once('error', error => {
            resolved = true;
            reject(error);
        });
        handle.process.once('exit', (code, signal) => {
            if (resolved)
                return;
            if (code === 0) {
                resolve();
            }
            else {
                signal = signal ? `${signal}:` : '';
                reject(new Error(`Child exited with ${signal}${code}`));
            }
        });
    });
    return Promise.resolve(handle);
}
774660
def ExecuteCmd(cmd, quiet=False):
  
  result = None
  if quiet:
    with open(os.devnull, "w") as fnull:
      result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull)
  else:
    result = subprocess.call(cmd, shell=True)
  return result
520191
def check_output(self, cmd):
        
        p = self.Popen(cmd, stdout=subprocess.PIPE)
        output, _ = p.communicate()
        if p.returncode != 0:
            raise RemoteCalledProcessError(p.returncode, cmd, self.host, output=output)
        return output
1148200
private function execCmd($cmd, &$stdout = null, &$stderr = null)
    {
        $descriptorspec = array(
            0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
            1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
            2 => array("pipe", "w")   // stderr is a file to write to
        );

        $pipes= array();
        $process = proc_open($cmd, $descriptorspec, $pipes);

        $stdout = "";
        $stderr = "";

        if (!is_resource($process)) {
            return false;
        }

        #close child's input imidiately
        fclose($pipes[0]);

        stream_set_blocking($pipes[1], false);
        stream_set_blocking($pipes[2], false);

        $todo= array($pipes[1],$pipes[2]);

        while (true) {
            $readstdout = [];
            $readstderr = [];

            if (false !== !feof($pipes[1])) {
                $readstdout[]= $pipes[1];
            }

            if (false !== !feof($pipes[2])) {
                $readstderr[]= $pipes[2];
            }

            if (empty($readstdout)) {
                break;
            }

            $write = null;
            $ex = null;
            $ready = stream_select($readstdout, $write, $ex, 2);

            if (false === $ready) {
                // probably dead process
                break;
            }

            foreach ($readstdout as $out) {
                $line = fread($out, 1024);
                $stdout.= $line;
            }

            foreach ($readstderr as $out) {
                $line = fread($out, 1024);
                $stderr.= $line;
            }
        }

        $stdout = strlen($stdout) > 0 ? $stdout : null;
        $stderr = strlen($stderr) > 0 ? $stderr : null;

        fclose($pipes[1]);
        fclose($pipes[2]);

        return proc_close($process);
    }
83889
def ipmi_method(self, command):       
        
        ipmi = ipmitool(self.console, self.password, self.username)
        
        if command == "reboot":
            self.ipmi_method(command="status")
            if self.output == "Chassis Power is off":
                command = "on"
        
        ipmi.execute(self.ipmi_map[command])
        
        if ipmi.status:
            self.error = ipmi.error.strip()
        else:
            self.output = ipmi.output.strip()        
        self.status = ipmi.status
496857
def Shell(device, *command):
    
    if command:
        return device.StreamingShell(' '.join(command))
    else:
        # Retrieve the initial terminal prompt to use as a delimiter for future reads
        terminal_prompt = device.InteractiveShell()
        print(terminal_prompt.decode('utf-8'))

        # Accept user input in a loop and write that into the interactive shells stdin, then print output
        while True:
            cmd = input('> ')
            if not cmd:
                continue
            elif cmd == 'exit':
                break
            else:
                stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
                if stdout:
                    if isinstance(stdout, bytes):
                        stdout = stdout.decode('utf-8')
                        print(stdout)

        device.Close()
243029
def exec(self, command_str, **command_env):
		
		env = self.__vars.copy()
		env.update(command_env)

		command_tokens = WCommandProto.split_command(command_str)
		command_obj = self.commands().select(*command_tokens, **env)
		if command_obj is None:
			raise WCommandSet.NoCommandFound('No suitable command found: "%s"' % command_str)

		result = command_obj.exec(*command_tokens, **env)
		self.__track_vars(result)
		return result
954667
def output_hook(output)
      idx = output.index(COMMAND_PREFIX)
      return yield output.gsub(@prompt, '') if idx.nil?

      yield output.slice!(0, idx)
      cmd, args = output.slice(COMMAND_PREFIX.size..-1).split(' ', 2)
      # only support ruby and pry now.
      return yield output unless %w[ruby pry rsource].include?(cmd)

      args = case cmd
             when 'pry' then '__send__(:invoke_pry)'
             when 'rsource' then File.read(File.expand_path(args.strip))
             else args
             end
      args = '__send__(:invoke_pry)' if cmd == 'pry'
      # gdb by default set tty
      # hack it
      `stty opost onlcr`
      begin
        eval_context.instance_eval(args)
      rescue StandardError, ScriptError => e
        $stdout.puts("#{e.class}: #{e}")
      end
      @tube.puts('END')
      @tube.readuntil(@prompt)
      nil
    end