Connect a Protocol to a ssh exec session
323884
def connectExec(connection, protocol, commandLine):
    
    deferred = connectSession(connection, protocol)
    @deferred.addCallback
    def requestSubsystem(session):
        return session.requestExec(commandLine)
    return deferred
1238608
def establish_scp_conn(self):
        """"""
        ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()
        self.scp_conn = self.ssh_ctl_chan._build_ssh_client()
        self.scp_conn.connect(**ssh_connect_params)
        self.scp_client = scp.SCPClient(self.scp_conn.get_transport())
210538
def exec_command(self):
        
        if not self.original_command_string:
            raise SSHEnvironmentError('no SSH command found; '
                                      'interactive shell disallowed.')

        command_info = {'from': self.get_client_ip(),
                        'keyname': self.keyname,
                        'ssh_original_comand': self.original_command_string,
                        'time': time.time()}

        os.environ['AUTHPROGS_KEYNAME'] = self.keyname

        retcode = 126
        try:
            match = self.find_match()
            command_info['command'] = match.get('command')
            self.logdebug('find_match returned "%s"\n' % match)

            command = match['command']
            retcode = subprocess.call(command)
            command_info['code'] = retcode
            self.log('result: %s\n' % command_info)
            sys.exit(retcode)
        except (CommandRejected, OSError) as err:
            command_info['exception'] = '%s' % err
            self.log('result: %s\n' % command_info)
            sys.exit(retcode)
1174405
def connect(self, protocol=None):
        """"""
        self._link.enter_debug(STLink.Protocol.SWD)
        self._is_connected = True
713553
def handle_ssh(self, mine=False):
        '''
        
        '''
        que = multiprocessing.Queue()
        running = {}
        target_iter = self.targets.__iter__()
        returned = set()
        rets = set()
        init = False
        while True:
            if not self.targets:
                log.error('No matching targets found in roster.')
                break
            if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
                try:
                    host = next(target_iter)
                except StopIteration:
                    init = True
                    continue
                for default in self.defaults:
                    if default not in self.targets[host]:
                        self.targets[host][default] = self.defaults[default]
                if 'host' not in self.targets[host]:
                    self.targets[host]['host'] = host
                if self.targets[host].get('winrm') and not HAS_WINSHELL:
                    returned.add(host)
                    rets.add(host)
                    log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
                    log.debug(log_msg)
                    no_ret = {'fun_args': [],
                              'jid': None,
                              'return': log_msg,
                              'retcode': 1,
                              'fun': '',
                              'id': host}
                    yield {host: no_ret}
                    continue
                args = (
                        que,
                        self.opts,
                        host,
                        self.targets[host],
                        mine,
                        )
                routine = MultiprocessingProcess(
                                target=self.handle_routine,
                                args=args)
                routine.start()
                running[host] = {'thread': routine}
                continue
            ret = {}
            try:
                ret = que.get(False)
                if 'id' in ret:
                    returned.add(ret['id'])
                    yield {ret['id']: ret['ret']}
            except Exception:
                # This bare exception is here to catch spurious exceptions
                # thrown by que.get during healthy operation. Please do not
                # worry about this bare exception, it is entirely here to
                # control program flow.
                pass
            for host in running:
                if not running[host]['thread'].is_alive():
                    if host not in returned:
                        # Try to get any returns that came through since we
                        # last checked
                        try:
                            while True:
                                ret = que.get(False)
                                if 'id' in ret:
                                    returned.add(ret['id'])
                                    yield {ret['id']: ret['ret']}
                        except Exception:
                            pass

                        if host not in returned:
                            error = ('Target \'{0}\' did not return any data, '
                                     'probably due to an error.').format(host)
                            ret = {'id': host,
                                   'ret': error}
                            log.error(error)
                            yield {ret['id']: ret['ret']}
                    running[host]['thread'].join()
                    rets.add(host)
            for host in rets:
                if host in running:
                    running.pop(host)
            if len(rets) >= len(self.targets):
                break
            # Sleep when limit or all threads started
            if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
                time.sleep(0.1)
871215
def _setup_ssh(self):
        """"""
        global paramiko
        if paramiko is none:
            import paramiko

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.server, username=self.user, pkey=self.pkey)
401572
def _connect(self):
        """"""
        self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._soc.connect((self._ipaddr, self._port))
        self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
                                       'sha': self._password}))
566205
def connect(host=nil, port=nil, &cb)
      host ||= opts[:upstream_host] || raise('no upstream host')
      port ||= opts[:upstream_port] || raise('no upstream port')
      cb   ||= lambda { |conn| opts[:session_callback].call(self, conn) }
      log.debug "Making upstream connection to #{host}:#{port}"
      EM.connect(host, port, Connection, opts[:upstream_args], &cb)
    end
488437
def ssh(self, *command):
        """"""
        if self.args.user:
            ssh_spec = '{0}@{1}'.format(self.args.user, self.args.server)
        else:
            ssh_spec = self.args.server

        return self.sh('ssh', ssh_spec, *command)
1120088
async def async_connect(self):
        """"""

        kwargs = {
            'username': self._username if self._username else None,
            'client_keys': [self._ssh_key] if self._ssh_key else None,
            'port': self._port,
            'password': self._password if self._password else None,
            'known_hosts': None
        }

        self._client = await asyncssh.connect(self._host, **kwargs)
        self._connected = True
1033544
def openssh_tunnel(self, lport, rport, server, remoteip='127.0.0.1',
                   keyfile=None, password=None, timeout=0.4):
    
    ssh = "ssh "
    if keyfile:
        ssh += "-i " + keyfile

    if ':' in server:
        server, port = server.split(':')
        ssh += " -p %s" % port

    cmd = "%s -O check %s" % (ssh, server)
    (output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
    if not exitstatus:
        pid = int(output[output.find("(pid=")+5:output.find(")")])
        cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % (
            ssh, lport, remoteip, rport, server)
        (output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
        if not exitstatus:
            atexit.register(_stop_tunnel, cmd.replace("-O forward",
                                                      "-O cancel",
                                                      1))
            return pid
    cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % (
                                  ssh, lport, remoteip, rport, server, timeout)

    # pop SSH_ASKPASS from env
    env = os.environ.copy()
    env.pop('SSH_ASKPASS', None)

    ssh_newkey = 'Are you sure you want to continue connecting'
    tunnel = pexpect.spawn(cmd, env=env)
    failed = False
    while True:
        try:
            i = tunnel.expect([ssh_newkey, '[Pp]assword:'], timeout=.1)
            if i == 0:
                host = server.split('@')[-1]
                question = _("The authenticity of host <b>%s</b> can't be "
                             "established. Are you sure you want to continue "
                             "connecting?") % host
                reply = QMessageBox.question(self, _('Warning'), question,
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.Yes:
                    tunnel.sendline('yes')
                    continue
                else:
                    tunnel.sendline('no')
                    raise RuntimeError(
                       _("The authenticity of the host can't be established"))
            if i == 1 and password is not None:
                tunnel.sendline(password)
        except pexpect.TIMEOUT:
            continue
        except pexpect.EOF:
            if tunnel.exitstatus:
                raise RuntimeError(_("Tunnel '%s' failed to start") % cmd)
            else:
                return tunnel.pid
        else:
            if failed or password is None:
                raise RuntimeError(_("Could not connect to remote host"))
                # TODO: Use this block when pyzmq bug #620 is fixed
                # # Prompt a passphrase dialog to the user for a second attempt
                # password, ok = QInputDialog.getText(self, _('Password'),
                #             _('Enter password for: ') + server,
                #             echo=QLineEdit.Password)
                # if ok is False:
                #      raise RuntimeError('Could not connect to remote host.')
            tunnel.sendline(password)
            failed = True
337272
function _initShell()
    {
        // connect using the sample parameters in protocol-1.5.txt.
        // according to wikipedia.org's entry on text terminals, "the fundamental type of application running on a text
        // terminal is a command line interpreter or shell".  thus, opening a terminal session to run the shell.
        $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, self::TTY_OP_END);

        if (!$this->_send_binary_packet($data)) {
            user_error('Error sending SSH_CMSG_REQUEST_PTY');
            return false;
        }

        $response = $this->_get_binary_packet();

        if ($response === true) {
            return false;
        }
        if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
            user_error('Expected SSH_SMSG_SUCCESS');
            return false;
        }

        $data = pack('C', NET_SSH1_CMSG_EXEC_SHELL);

        if (!$this->_send_binary_packet($data)) {
            user_error('Error sending SSH_CMSG_EXEC_SHELL');
            return false;
        }

        $this->bitmap |= self::MASK_SHELL;

        //stream_set_blocking($this->fsock, 0);

        return true;
    }
865328
def connect(self, protocolFactory):
        
        deferred = self._startProcess()
        deferred.addCallback(self._connectRelay, protocolFactory)
        deferred.addCallback(self._startRelay)
        return deferred
1239176
def exec!(command, opts = {}, &block)
      $stdout.puts(command.to_s.blue) if verbose
      @ssh.exec! command, &block
    end
752492
def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):
    
    ssh_version = subprocess.check_output(['ssh', '-V'],
                                          stderr=subprocess.STDOUT)
    log.debug('local SSH version: %r', ssh_version)
    environ = {'SSH_AUTH_SOCK': sock_path, 'SSH_AGENT_PID': str(os.getpid())}
    device_mutex = threading.Lock()
    with server.unix_domain_socket_server(sock_path) as sock:
        sock.settimeout(timeout)
        quit_event = threading.Event()
        handle_conn = functools.partial(server.handle_connection,
                                        handler=handler,
                                        mutex=device_mutex)
        kwargs = dict(sock=sock,
                      handle_conn=handle_conn,
                      quit_event=quit_event)
        with server.spawn(server.server_thread, kwargs):
            try:
                yield environ
            finally:
                log.debug('closing server')
                quit_event.set()
196036
def ssh(ctx, instance_id, instance_name, username, key_file, port, ssh_options, private_ip,
        gateway_instance_id, gateway_username, dry_run):
    """"""
    session = create_session(ctx.obj['AWS_PROFILE_NAME'])

    if instance_id is None and instance_name is None:
        click.echo(
            "One of --instance-id/-i or --instance-name/-n"
            " has to be specified.", err=True)
        sys.exit(1)
    elif instance_id is not None and instance_name is not None:
        click.echo(
            "Both --instance-id/-i and --instance-name/-n "
            "can't to be specified at the same time.", err=True)
        sys.exit(1)
    cmd = create_ssh_command(
        session, instance_id, instance_name, username, key_file, port, ssh_options, private_ip,
        gateway_instance_id, gateway_username)
    if not dry_run:
        subprocess.call(cmd, shell=True)
    else:
        click.echo(cmd)
670705
def ssh(self, *args, **kwargs):
        '''
        
        '''
        ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts,
                                                      disable_custom_roster=True)
        return ssh_client.cmd_sync(kwargs)