Attempt to authenticate to the given transport using any of the private
    keys available from an SSH agent.
1108
def agent_auth(transport, username):
    
    
    agent = ssh.Agent()
    agent_keys = agent.get_keys()
    if len(agent_keys) == 0:
        return
        
    for key in agent_keys:
        print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()),
        try:
            transport.auth_publickey(username, key)
            print '... success!'
            return
        except ssh.SSHException:
            print '... nope.'
1003839
def load_key(key_str, key_pass):
        

        try:
            # First try to parse as a p12 file
            key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass)
        except ValueError as e:
            # If it fails due to invalid password raise error here
            if e.args[0] == 'Password provided is invalid':
                raise AS2Exception('Password not valid for Private Key.')

            # if not try to parse as a pem file
            key, cert = None, None
            for kc in split_pem(key_str):
                try:
                    cert = asymmetric.load_certificate(kc)
                except (ValueError, TypeError):
                    try:
                        key = asymmetric.load_private_key(kc, key_pass)
                    except OSError:
                        raise AS2Exception(
                            'Invalid Private Key or password is not correct.')

        if not key or not cert:
            raise AS2Exception(
                'Invalid Private key file or Public key not included.')

        return key, cert
253812
def _create_ssh_keys(self):
        
        ret, _, _ = utils.run_command(
            [
                'ssh-keygen',
                '-t',
                'rsa',
                '-m',
                'PEM',
                '-N',
                '',
                '-f',
                self.paths.ssh_id_rsa(),
            ]
        )
        if ret != 0:
            raise RuntimeError(
                'Failed to crate ssh keys at %s',
                self.paths.ssh_id_rsa(),
            )
713272
def _Authenticate(self):
		""""""
		super(HttpRpcServer, self)._Authenticate()
		if self.save_cookies:
			StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
			self.cookie_jar.save()
34308
def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
    
    return authenticate_with_certificate_chain(
        reactor, base_url, [client_cert], client_key, ca_cert,
    )
101831
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
    
    key = private_key.exportKey()
    return HTTPSignatureHeaderAuth(
        headers=["(request-target)", "user-agent", "host", "date"],
        algorithm="rsa-sha256",
        key=key,
        key_id=private_key_id,
    )
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
1266158
def ssh_session(key_filename,
                username,
                ip_address,
                *cli):
    
    local('ssh -t -i %s %s@%s %s' % (key_filename,
                                     username,
                                     ip_address,
                                     "".join(chain.from_iterable(cli))))
763935
def create_transport(host, connect_timeout, ssl=False):
    """"""
    if ssl:
        return SSLTransport(host, connect_timeout, ssl)
    else:
        return TCPTransport(host, connect_timeout)
654360
def authenticate
      if RbConfig::CONFIG["target_os"] =~ /freebsd/
        @socket.sendmsg(0.chr, 0, nil, [:SOCKET, :SCM_CREDS, ""])
      else
        @socket.write(0.chr)
      end
      next_authenticator
      @state = :Starting
      while @state != :Authenticated
        r = next_state
        return r if !r
      end
      true
    end
622830
def _connect_to_gateway(self):
        
        for key in self.ssh_pkeys:
            self.logger.debug('Trying to log in with key: {0}'
                              .format(hexlify(key.get_fingerprint())))
            try:
                self._transport = self._get_transport()
                self._transport.connect(hostkey=self.ssh_host_key,
                                        username=self.ssh_username,
                                        pkey=key)
                if self._transport.is_alive:
                    return
            except paramiko.AuthenticationException:
                self.logger.debug('Authentication error')
                self._stop_transport()

        if self.ssh_password:  # avoid conflict using both pass and pkey
            self.logger.debug('Trying to log in with password: {0}'
                              .format('*' * len(self.ssh_password)))
            try:
                self._transport = self._get_transport()
                self._transport.connect(hostkey=self.ssh_host_key,
                                        username=self.ssh_username,
                                        password=self.ssh_password)
                if self._transport.is_alive:
                    return
            except paramiko.AuthenticationException:
                self.logger.debug('Authentication error')
                self._stop_transport()

        self.logger.error('Could not open connection to gateway')
698677
def _authenticate(self):
        
        url = "{base_url}/api/authenticate".format(base_url=self._base_url())
        data = json.dumps({'username': self.username, "password": self.password})
        # Bypass authentication check in make_request by using _send_request
        logger.debug("Authenticating against NetMRI")
        self._send_request(url, method="post", data=data)
        self._is_authenticated = True
393801
def pkdecrypt(self, conn):
        """"""
        for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
            keyring.sendline(conn, msg)

        line = keyring.recvline(conn)
        assert keyring.recvline(conn) == b'END'
        remote_pubkey = parse_ecdh(line)

        identity = self.get_identity(keygrip=self.keygrip)
        ec_point = self.client.ecdh(identity=identity, pubkey=remote_pubkey)
        keyring.sendline(conn, b'D ' + _serialize_point(ec_point))
831684
def _get_private_key(cls, private_key_path, private_key_passphrase):
        """"""
        if private_key_path is None or private_key_passphrase is None:
            return None

        with open(private_key_path, 'rb') as key:
            p_key = serialization.load_pem_private_key(
                key.read(),
                password=private_key_passphrase.encode(),
                backend=default_backend())

        return p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())
584762
def parse_ssh_destination(destination):
    
    match = _re_ssh.match(destination)
    if not match:
        raise InvalidDestination("Invalid destination: %s" % destination)
    user, password, host, port = match.groups()
    info = {}
    if user:
        info['username'] = user
    else:
        info['username'] = getpass.getuser()
    if password:
        info['password'] = password
    if port:
        info['port'] = int(port)
    info['hostname'] = host

    return info
1015823
def ssh_args(conn):
    """"""
    I, = conn.identities
    identity = I.identity_dict
    pubkey_tempfile, = conn.public_keys_as_files()

    args = []
    if 'port' in identity:
        args += ['-p', identity['port']]
    if 'user' in identity:
        args += ['-l', identity['user']]

    args += ['-o', 'IdentityFile={}'.format(pubkey_tempfile.name)]
    args += ['-o', 'IdentitiesOnly=true']
    return args + [identity['host']]
985258
def authenticate(api_key, api_url, **kwargs):
    """"""

    muddle = Muddle(**kwargs)

    # Login.
    muddle.authenticate(api_key, api_url)
    return muddle