Connect to a single host. Returns the SSH client if succesful. Stateless by
    design so can be run in parallel.
182049
def connect(state, host, for_fact=None):
    '''
    
    '''

    kwargs = _make_paramiko_kwargs(state, host)
    logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs))

    # Hostname can be provided via SSH config (alias), data, or the hosts name
    hostname = kwargs.pop(
        'hostname',
        host.data.ssh_hostname or host.name,
    )

    try:
        # Create new client & connect to the host
        client = SSHClient()
        client.set_missing_host_key_policy(MissingHostKeyPolicy())
        client.connect(hostname, **kwargs)

        # Enable SSH forwarding
        session = client.get_transport().open_session()
        AgentRequestHandler(session)

        # Log
        log_message = '{0}{1}'.format(
            host.print_prefix,
            click.style('Connected', 'green'),
        )

        if for_fact:
            log_message = '{0}{1}'.format(
                log_message,
                ' (for {0} fact)'.format(for_fact),
            )

        logger.info(log_message)

        return client

    except AuthenticationException:
        auth_kwargs = {}

        for key, value in kwargs.items():
            if key in ('username', 'password'):
                auth_kwargs[key] = value
                continue

            if key == 'pkey' and value:
                auth_kwargs['key'] = host.data.ssh_key

        auth_args = ', '.join(
            '{0}={1}'.format(key, value)
            for key, value in auth_kwargs.items()
        )

        _log_connect_error(host, 'Authentication error', auth_args)

    except SSHException as e:
        _log_connect_error(host, 'SSH error', e)

    except gaierror:
        _log_connect_error(host, 'Could not resolve hostname', hostname)

    except socket_error as e:
        _log_connect_error(host, 'Could not connect', e)

    except EOFError as e:
        _log_connect_error(host, 'EOF error', e)
1206474
def get_connection(self, *args, **kwargs):
        
        conn = super(SSLHTTPAdapter, self).get_connection(*args, **kwargs)
        if conn.assert_hostname != self.assert_hostname:
            conn.assert_hostname = self.assert_hostname
        return conn
576630
def connect(self, hostname=None, port=None):
        
        if hostname is not None:
            self.host = hostname
        conn = self._connect_hook(self.host, port)
        self.os_guesser.protocol_info(self.get_remote_version())
        self.auto_driver = driver_map[self.guess_os()]
        if self.get_banner():
            self.os_guesser.data_received(self.get_banner(), False)
        return conn
116788
def _connect(self):
        
        server = self.servers.peek()
        try:
            self.connect(
                server.host, server.port, self._nickname,
                server.password, ircname=self._realname,
                **self.__connect_params)
        except irc.client.ServerConnectionError:
            pass
194700
def get_connection(self, host, port):
        
        return beanstalkc.Connection(
            host=host,
            port=port
        )
1294295
def connect(self):
        
        future = concurrent.Future()

        if self.connected:
            raise exceptions.ConnectError('already connected')

        LOGGER.debug('%s connecting', self.name)
        self.io_loop.add_future(
            self._client.connect(self.host, self.port),
            lambda f: self._on_connected(f, future))
        return future
892339
def connect(self):
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("127.0.0.1", self._port))
    return sock
1092596
def connect(self, host=None, port=None):
        """"""
        host = self.host if host is None else host
        port = self.port if port is None else port
        self.socket.connect(host, port)
244949
def needs_ssh(hostname, _socket=None):
    
    if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:
        return False
    _socket = _socket or socket
    fqdn = _socket.getfqdn()
    if hostname == fqdn:
        return False
    local_hostname = _socket.gethostname()
    local_short_hostname = local_hostname.split('.')[0]
    if local_hostname == hostname or local_short_hostname == hostname:
        return False
    return True
742383
def ssh_client(host, username=None, password=None, **kwargs):
    
    client = paramiko.SSHClient()
    # save hostname and username on the instance - this is a ugly hack
    # but I don't see any other way to do that for now. Note that
    # this is only used for SshSession.__str__.
    client.hostname = host
    client.username = username
    if username is not None:
        kwargs['username'] = username
    if password is not None:
        kwargs['password'] = password
    if username is not None and password is not None:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        kwargs.setdefault('look_for_keys', False)
    client.connect(host, **kwargs)
    return client
886258
def connect(self, host, port, name=None):
        
        client = self._clients.get(name)
        client.connect_to(host, port)
610855
def connect_hostport(hostport, timeout=RPC_DEFAULT_TIMEOUT, my_hostport=None):
    
    host, port = url_to_host_port(hostport)

    assert host is not None and port is not None

    protocol = url_protocol(hostport)
    if protocol is None:
        log.warning("No scheme given in {}. Guessing by port number".format(hostport))
        if port == RPC_SERVER_PORT or port == RPC_SERVER_TEST_PORT:
            protocol = 'http'
        else:
            protocol = 'https'

    proxy = BlockstackRPCClient(host, port, timeout=timeout, src=my_hostport, protocol=protocol)
    return proxy
1254895
async def _connect(self, hostname, port, reconnect=False, password=None, encoding=pydle.protocol.DEFAULT_ENCODING, channels=[], tls=False, tls_verify=False, source_address=None):
        
        self.password = password

        # Create connection if we can't reuse it.
        if not reconnect:
            self._autojoin_channels = channels
            self.connection = connection.Connection(hostname, port,
                source_address=source_address,
                tls=tls, tls_verify=tls_verify,
                tls_certificate_file=self.tls_client_cert,
                tls_certificate_keyfile=self.tls_client_cert_key,
                tls_certificate_password=self.tls_client_cert_password,
                eventloop=self.eventloop)
            self.encoding = encoding

        # Connect.
        await self.connection.connect()
388971
def connectPeer(self, peer):
        
        return self.conns.connectCached(endpoint.Q2QEndpoint(self.svc,
                                                             self.addr,
                                                             peer,
                                                             PROTOCOL_NAME),
                                        self.clientFactory)
577525
def _connect(self):
        
        if not statsd:
            return

        if hasattr(statsd, 'StatsClient'):
            self.connection = statsd.StatsClient(
                host=self.host,
                port=self.port
            ).pipeline()
        else:
            # Create socket
            self.connection = statsd.Connection(
                host=self.host,
                port=self.port,
                sample_rate=1.0
            )
740555
def start(self):
        
        if self.via_ip:
            connect_to = self.via_ip
            self.description = '[%s@%s via %s]' % (self._user,
                                                   self._hostname,
                                                   self.via_ip)
        else:
            connect_to = self._hostname
            self.description = '[%s@%s]' % (self._user,
                                            self._hostname)

        exception = None
        for i in range(60):
            try:
                self._client.connect(
                    connect_to,
                    username=self._user,
                    allow_agent=True,
                    key_filename=self._key_filename)
            # NOTE(Gonéri): TypeError is in the list because of
            # https://github.com/paramiko/paramiko/issues/615
                self._transport = self._get_transport()
            except (OSError,
                    TypeError,
                    ssh_exception.SSHException,
                    ssh_exception.NoValidConnectionsError) as e:
                exception = e
                LOG.info('%s waiting for %s: %s' %
                         (self.description, connect_to, str(exception)))
                time.sleep(1)
            else:
                LOG.debug('%s connected' % self.description)
                self._started = True
                return

        _error = ("unable to connect to ssh service on '%s': %s" %
                  (self._hostname, str(exception)))
        LOG.error(_error)
        raise exception
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;
    }