Establish ssh connection and return paramiko client.

    Raises:
        IpaSSHException: If connection cannot be established
            in given number of attempts.
964343
def establish_ssh_connection(ip,
                             ssh_private_key_file,
                             ssh_user,
                             port,
                             attempts=5,
                             timeout=None):
    
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    while attempts:
        try:
            client.connect(
                ip,
                port=port,
                username=ssh_user,
                key_filename=ssh_private_key_file,
                timeout=timeout
            )
        except:  # noqa: E722
            attempts -= 1
            time.sleep(10)
        else:
            return client

    raise IpaSSHException(
        'Failed to establish SSH connection to instance.'
    )
363965
def _connect(self):
        
        ssh = self._ssh_client()
        logger.debug("Connecting with %s",
                     ', '.join('%s=%r' % (k, v if k != "password" else "***")
                               for k, v in iteritems(self.destination)))
        ssh.connect(**self.destination)
        logger.debug("Connected to %s", self.destination['hostname'])
        self._ssh = ssh
225456
def _ssh_client(self):
        
        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
        return ssh
591446
private SshConnection connect() {
        if (sshConnection != null && sshConnection.isConnected()) {
            return sshConnection;
        }
        while (!shutdownInProgress) {
            SshConnection ssh = null;
            try {
                logger.debug("Connecting...");
                ssh = SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy,
                        authentication, authenticationUpdater);
                gerritVersion  = formatVersion(ssh.executeCommand("gerrit version"));
                logger.debug("connection seems ok, returning it.");
                return ssh;
            } catch (SshConnectException sshConEx) {
                logger.error("Could not connect to Gerrit server! "
                        + "Host: {} Port: {}", gerritHostName, gerritSshPort);
                logger.error(" Proxy: {}", gerritProxy);
                logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
                logger.error("ConnectionException: ", sshConEx);
            } catch (SshAuthenticationException sshAuthEx) {
                logger.error("Could not authenticate to Gerrit server!"
                        + "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}",
                        new Object[]{authentication.getUsername(),
                                authentication.getPrivateKeyFile(),
                                authentication.getPrivateKeyFilePassword(), });
                logger.error("AuthenticationException: ", sshAuthEx);
            } catch (IOException ex) {
                logger.error("Could not connect to Gerrit server! "
                        + "Host: {} Port: {}", gerritHostName, gerritSshPort);
                logger.error(" Proxy: {}", gerritProxy);
                logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
                logger.error("IOException: ", ex);
            }

            if (ssh != null) {
                logger.trace("Disconnecting bad connection.");
                try {
                    //The ssh lib used is starting at least one thread for each connection.
                    //The thread isn't shutdown properly when the connection goes down,
                    //so we need to close it "manually"
                    ssh.disconnect();
                } catch (Exception ex) {
                    logger.warn("Error when disconnecting bad connection.", ex);
                } finally {
                    ssh = null;
                }
            }

            if (!shutdownInProgress) {
                //If we end up here, sleep for a while and then go back up in the loop.
                logger.trace("Sleeping for a bit.");
                try {
                    Thread.sleep(CONNECT_SLEEP);
                } catch (InterruptedException ex) {
                    logger.warn("Got interrupted while sleeping.", ex);
                }
            }
        }
        return null;
    }
405915
def connect(self):
        

        # Make sure we're in client mode
        if self.mode and self.mode != 'client':
            raise ValueError("%s is not in client mode" %
                             self.__class__.__name__)
        self.mode = 'client'

        # If we're connected, nothing to do
        if self.conn:
            return

        # OK, attempt the connection
        fd = socket.create_connection((self.host, self.port))

        # Initialize the connection object
        self.conn = self.connection_class(fd)

        # Authenticate
        try:
            self.conn.send('AUTH', self.authkey)
            cmd, payload = self.conn.recv()
            if cmd != 'OK':
                LOG.error("Failed to authenticate to %s port %s: %s" %
                          (self.host, self.port, payload[0]))
                self.close()
        except Exception:
            exc_type, exc_value, exc_tb = sys.exc_info()

            # Log the error
            if exc_type == ValueError:
                LOG.error("Received bogus response from server: %s" %
                          str(exc_value))
            elif exc_type == ConnectionClosed:
                LOG.error("%s while authenticating to server" %
                          str(exc_value))
            else:
                LOG.exception("Failed to authenticate to server")

            # Close the connection
            self.close()

            # Re-raise the exception
            raise exc_type, exc_value, exc_tb
1206270
def get_ssh_client(ip,
                   ssh_private_key_file,
                   ssh_user='root',
                   port=22,
                   timeout=600,
                   wait_period=10):
    """"""
    if ip in CLIENT_CACHE:
        return CLIENT_CACHE[ip]

    start = time.time()
    end = start + timeout

    client = None
    while time.time() < end:
        try:
            client = establish_ssh_connection(
                ip,
                ssh_private_key_file,
                ssh_user,
                port,
                timeout=wait_period
            )
            execute_ssh_command(client, 'ls')
        except:  # noqa: E722
            if client:
                client.close()
            wait_period += wait_period
        else:
            CLIENT_CACHE[ip] = client
            return client

    raise IpaSSHException(
        'Attempt to establish SSH connection failed.'
    )
542608
def ssh(*arguments)
      options = []

      # Add the -p option if an alternate destination port is given
      if @uri.port
        options += ['-p', @uri.port.to_s]
      end

      # append the SSH URI
      options << ssh_uri

      # append the additional arguments
      arguments.each { |arg| options << arg.to_s }

      return system('ssh',*options)
    end
323884
def connectExec(connection, protocol, commandLine):
    
    deferred = connectSession(connection, protocol)
    @deferred.addCallback
    def requestSubsystem(session):
        return session.requestExec(commandLine)
    return deferred
146938
def ssh_client(host):
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host)
    return ssh
1094418
def start(io)
      # start SSL negotiation
      ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx)
      # connect to server socket
      ssl.accept
      # make sure to close also the underlying io
      ssl.sync_close = true
      # return as new io socket
      return ssl
    end
697340
def create_bitcoind_connection( rpc_username, rpc_password, server, port, use_https, timeout ):
    
    
    from .bitcoin_blockchain import AuthServiceProxy

    global do_wrap_socket, create_ssl_authproxy
        
    log.debug("[%s] Connect to bitcoind at %s://%s@%s:%s, timeout=%s" % (os.getpid(), 'https' if use_https else 'http', rpc_username, server, port, timeout) )
    
    protocol = 'https' if use_https else 'http'
    if not server or len(server) < 1:
        raise Exception('Invalid bitcoind host address.')
    if not port or not is_valid_int(port):
        raise Exception('Invalid bitcoind port number.')
    
    authproxy_config_uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port)
    
    if use_https:
        # TODO: ship with a cert
        if do_wrap_socket:
           # ssl._create_unverified_context and ssl.create_default_context are not supported.
           # wrap the socket directly 
           connection = BitcoindConnection( server, int(port), timeout=timeout )
           ret = AuthServiceProxy(authproxy_config_uri, connection=connection)
           
        elif create_ssl_authproxy:
           # ssl has _create_unverified_context, so we're good to go 
           ret = AuthServiceProxy(authproxy_config_uri, timeout=timeout)
        
        else:
           # have to set up an unverified context ourselves 
           ssl_ctx = ssl.create_default_context()
           ssl_ctx.check_hostname = False
           ssl_ctx.verify_mode = ssl.CERT_NONE
           connection = httplib.HTTPSConnection( server, int(port), context=ssl_ctx, timeout=timeout )
           ret = AuthServiceProxy(authproxy_config_uri, connection=connection)
          
    else:
        ret = AuthServiceProxy(authproxy_config_uri)

    # remember the options 
    bitcoind_opts = {
       "bitcoind_user": rpc_username,
       "bitcoind_passwd": rpc_password,
       "bitcoind_server": server,
       "bitcoind_port": port,
       "bitcoind_use_https": use_https,
       "bitcoind_timeout": timeout
    }
    
    setattr( ret, "opts", bitcoind_opts )
    return ret
440096
def start(self):
        
        username = self.options['username']
        password = self.options['password']
        server_host = self.options['server']
        server_port = self.options['port']
        honeypot_id = self.options['honeypot_id']

        session = self.create_session(server_host, server_port, honeypot_id)

        self.sessions[session.id] = session
        logger.debug(
            'Sending ssh bait session to {0}:{1}. (bait id: {2})'.format(server_host, server_port, session.id))
        try:
            self.connect_login()
            session.did_connect = True
            # TODO: Handle failed login
            session.add_auth_attempt('plaintext', True, username=username, password=password)
            session.did_login = True
        except (SSHException, AuthenticationFailed) as err:
            logger.debug('Caught exception: {0} ({1})'.format(err, str(type(err))))
        else:
            command_count = 0
            command_limit = random.randint(6, 11)
            while command_count < command_limit:
                command_count += 1
                self.sense()
                comm, param = self.decide()
                self.act(comm, param)
                gevent.sleep(random.uniform(0.4, 5.6))
            self.logout()
            session.did_complete = True
        finally:
            session.alldone = True
            session.end_session()
            self.comm_chan.close()
791928
def remote_ssh(self, host):
        
        logger.info('Starting remote execution of task {0} on host {1}'.format(self.name, host['hostname']))
        try:
            self.remote_client = paramiko.SSHClient()
            self.remote_client.load_system_host_keys()
            self.remote_client.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())
            self.remote_client.connect(host['hostname'], username=host['user'],
                                       key_filename=host['identityfile'][0],
                                       timeout=82800)
            transport = self.remote_client.get_transport()
            transport.set_keepalive(10)

            self.remote_channel = transport.open_session()
            self.remote_channel.get_pty()
            self.remote_channel.exec_command(self.command)
        except Exception as e:
            logger.warn('Exception encountered in remote task execution')
            self.remote_failure = True
            self.stderr += 'Exception when trying to SSH related to: '
            self.stderr += '{0}: {1}\n"'.format(type(e).__name__, str(e))
            self.stderr += 'Was looking for host "{0}"\n'.format(str(host))
            self.stderr += 'Found in config:\n'
            self.stderr += 'host: "{0}"\n'.format(str(host))
            self.stderr += 'hostname: "{0}"\n'.format(str(host.get('hostname')))
            self.stderr += 'user: "{0}"\n'.format(str(host.get('user')))
            self.stderr += 'identityfile: "{0}"\n'.format(str(host.get('identityfile')))
            self.remote_client.close()
200608
def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True, 
                        verbosity=0):
    

    with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh:
        ssh_cb(ssh)
512400
def init(opts=None):
    '''
    
    '''
    if opts is None:
        opts = __opts__
    try:
        DETAILS[_worker_name()] = SSHConnection(
            host=opts['proxy']['host'],
            username=opts['proxy']['username'],
            password=opts['proxy']['password'],
            key_accept=opts['proxy'].get('key_accept', False),
            ssh_args=opts['proxy'].get('ssh_args', ''),
            prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
        DETAILS[_worker_name()].sendline('no cli session paging enable')

    except TerminalException as e:
        log.error(e)
        return False
    DETAILS['initialized'] = True
688091
function (options, callback) {
    let me = this
    let tunnel
    let sshcfg = {
      host: this.host + ':' + (options.sshport || 22),
      user: options.username,
      remoteport: this.port
    }

    if (options.password) {
      sshcfg.password = options.password
    }

    if (options.key) {
      sshcfg.key = options.key
    }

    // Dynamically determine port by availability or via option.
    // Then open the tunnel.
    if (options.port) {
      sshcfg.port = options.port
      tunnel = new NGN.Tunnel(sshcfg)
      tunnel.on('ready', function () {
        NGN.BUS.emit('sshtunnel.create', tunnel)
        callback && callback(me.host, options.port)
      })
      tunnel.connect()
    } else {
      // Create a quick TCP server on random port to secure the port,
      // then shut it down and use the newly freed port.
      let tmp = net.createServer().listen(0, '127.0.0.1', function () {
        sshcfg.port = this.address().port
        tmp.close()
      })

      tmp.on('close', function () {
        // Launch the tunnel
        tunnel = new NGN.Tunnel(sshcfg)
        tunnel.on('ready', function () {
          callback && callback('127.0.0.1', sshcfg.port)
        })
        tunnel.connect()
      })
    }
  }
318900
def __connect(hostname, timeout=20, username=None, password=None):
    '''
    
    '''
    drac_cred = __opts__.get('drac')
    err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' \
              'fields beneath a \'drac\' key in the master configuration file. Or you can ' \
              'pass in a username and password as kwargs at the CLI.'

    if not username:
        if drac_cred is None:
            log.error(err_msg)
            return False
        username = drac_cred.get('username', None)
    if not password:
        if drac_cred is None:
            log.error(err_msg)
            return False
        password = drac_cred.get('password', None)

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(hostname, username=username, password=password, timeout=timeout)
    except Exception as e:
        log.error('Unable to connect to %s: %s', hostname, e)
        return False

    return client