SSH agents — Paramiko documentation

# SSH agents

SSH Agent interface

class paramiko.agent.Agent

  Client interface for using private keys from an SSH agent running on the local machine. If an SSH agent is running, this class can be used to connect to it and retrieve `PKey` objects which can be used when attempting to authenticate to remote SSH servers.

  Upon initialization, a session with the local machine’s SSH agent is opened, if one is running. If no agent is running, initialization will succeed, but `get_keys` will return an empty tuple.

  Raises:

    `SSHException` – if an SSH agent is found, but speaks an incompatible protocol

  Changed in version 2.10: Added support for native openssh agent on windows (extending previous putty pageant support)

  close()

    Close the SSH agent connection.

  get_keys()

    Return the list of keys available through the SSH agent, if any. If no SSH agent was running (or it couldn’t be contacted), an empty list will be returned.

    This method performs no IO, just returns the list of keys retrieved when the connection was made.

    Returns:

      a tuple of `AgentKey` objects representing keys available on the SSH agent

class paramiko.agent.AgentClientProxy(chanRemote)

  Class proxying request as a client:

  1. client ask for a request_forward_agent()

  2. server creates a proxy and a fake SSH Agent

  3. server ask for establishing a connection when needed, calling the forward_agent_handler at client side.

  4. the forward_agent_handler launch a thread for connecting the remote fake agent and the local agent

  5. Communication occurs …

  close()

    Close the current connection and terminate the agent Should be called manually

  connect()

    Method automatically called by `AgentProxyThread.run`.

class paramiko.agent.AgentKey(agent, blob, comment='')

  Private key held in a local SSH agent. This type of key can be used for authenticating to a remote server (signing). Most other key operations work as expected.

  Changed in version 3.2: Added the `comment` kwarg and attribute.

  Changed in version 3.2: Added the `.inner_key` attribute holding a reference to the ‘real’ key instance this key is a proxy for, if one was obtainable, else None.

  property algorithm_name

    Return the key algorithm identifier for this key.

    Similar to `get_name`, but aimed at pure algorithm name instead of SSH protocol field value.

  asbytes()

    Return a string of an SSH `Message` made up of the public part(s) of this key. This string is suitable for passing to `__init__` to re-create the key object later.

  can_sign()

    Return `True` if this key has the private part necessary for signing data.

  property fingerprint

    Modern fingerprint property designed to be comparable to OpenSSH.

    Currently only does SHA256 (the OpenSSH default).

    New in version 3.2.

  static from_path(path, passphrase=None)

    Attempt to instantiate appropriate key subclass from given file path.

    Parameters:

      path (Path) – The path to load (may also be a `str`).

    Returns:

      A `PKey` subclass instance.

    Raises:

      `UnknownKeyType`, if our crypto backend doesn’t know this key type.

    New in version 3.2.

  classmethod from_private_key(file_obj, password=None)

    Create a key object by reading a private key from a file (or file-like) object. If the private key is encrypted and `password` is not `None`, the given password will be used to decrypt the key (otherwise `PasswordRequiredException` is thrown).

    Parameters:

      - file_obj – the file-like object to read from

      - password (str) – an optional password to use to decrypt the key, if it’s encrypted

    Returns:

      a new `PKey` based on the given private key

    Raises:

      `IOError` – if there was an error reading the key

    Raises:

      `PasswordRequiredException` – if the private key file is encrypted, and `password` is `None`

    Raises:

      `SSHException` – if the key file is invalid

  classmethod from_private_key_file(filename, password=None)

    Create a key object by reading a private key file. If the private key is encrypted and `password` is not `None`, the given password will be used to decrypt the key (otherwise `PasswordRequiredException` is thrown). Through the magic of Python, this factory method will exist in all subclasses of PKey (such as `RSAKey` or `DSSKey`), but is useless on the abstract PKey class.

    Parameters:

      - filename (str) – name of the file to read

      - password (str) – an optional password to use to decrypt the key file, if it’s encrypted

    Returns:

      a new `PKey` based on the given private key

    Raises:

      `IOError` – if there was an error reading the file

    Raises:

      `PasswordRequiredException` – if the private key file is encrypted, and `password` is `None`

    Raises:

      `SSHException` – if the key file is invalid

  static from_type_string(key_type, key_bytes)

    Given type `str` & raw `bytes`, return a `PKey` subclass instance.

    For example, `PKey.from_type_string("ssh-ed25519", <public bytes>)` will (if successful) return a new `Ed25519Key`.

    Parameters:

      - key_type (str) – The key type, eg `"ssh-ed25519"`.

      - key_bytes (bytes) – The raw byte data forming the key material, as expected by subclasses’ `data` parameter.

    Returns:

      A `PKey` subclass instance.

    Raises:

      `UnknownKeyType`, if no registered classes knew about this type.

    New in version 3.2.

  get_base64()

    Return a base64 string containing the public part of this key. Nothing secret is revealed. This format is compatible with that used to store public key files or recognized host keys.

    Returns:

      a base64 `string` containing the public part of the key.

  get_bits()

    Return the number of significant bits in this key. This is useful for judging the relative security of a key.

    Returns:

      bits in the key (as an `int`)

  get_fingerprint()

    Return an MD5 fingerprint of the public part of this key. Nothing secret is revealed.

    Returns:

      a 16-byte `string` (binary) of the MD5 fingerprint, in SSH format.

  get_name()

    Return the name of this private key implementation.

    Returns:

      name of this private key type, in SSH terminology, as a `str` (for example, `"ssh-rsa"`).

  classmethod identifiers()

    returns an iterable of key format/name strings this class can handle.

    Most classes only have a single identifier, and thus this default implementation suffices; see `ECDSAKey` for one example of an override.

  load_certificate(value)

    Supplement the private key contents with data loaded from an OpenSSH public key (`.pub`) or certificate (`-cert.pub`) file, a string containing such a file, or a `Message` object.

    The .pub contents adds no real value, since the private key file includes sufficient information to derive the public key info. For certificates, however, this can be used on the client side to offer authentication requests to the server based on certificate instead of raw public key.

    See: https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys

    Note: very little effort is made to validate the certificate contents, that is for the server to decide if it is good enough to authenticate successfully.

  sign_ssh_data(data, algorithm=None)

    Sign a blob of data with this private key, and return a `Message` representing an SSH signature message.

    Parameters:

      - data (bytes) – the data to sign.

      - algorithm (str) – the signature algorithm to use, if different from the key’s internal name. Default: `None`.

    Returns:

      an SSH signature `message`.

    Changed in version 2.9: Added the `algorithm` kwarg.

  verify_ssh_sig(data, msg)

    Given a blob of data, and an SSH message representing a signature of that data, verify that it was signed with this key.

    Parameters:

      - data (bytes) – the data that was signed.

      - msg (.Message) – an SSH signature message

    Returns:

      `True` if the signature verifies correctly; `False` otherwise.

  write_private_key(file_obj, password=None)

    Write private key contents into a file (or file-like) object. If the password is not `None`, the key is encrypted before writing.

    Parameters:

      - file_obj – the file-like object to write into

      - password (str) – an optional password to use to encrypt the key

    Raises:

      `IOError` – if there was an error writing to the file

    Raises:

      `SSHException` – if the key is invalid

  write_private_key_file(filename, password=None)

    Write private key contents into a file. If the password is not `None`, the key is encrypted before writing.

    Parameters:

      - filename (str) – name of the file to write

      - password (str) – an optional password to use to encrypt the key file

    Raises:

      `IOError` – if there was an error writing the file

    Raises:

      `SSHException` – if the key is invalid

class paramiko.agent.AgentLocalProxy(agent)

  Class to be used when wanting to ask a local SSH Agent being asked from a remote fake agent (so use a unix socket for ex.)

  property daemon

    A boolean value indicating whether this thread is a daemon thread.

    This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

    The entire Python program exits when only daemon threads are left.

  getName()

    Return a string used for identification purposes only.

    This method is deprecated, use the name attribute instead.

  get_connection()

    Return a pair of socket object and string address.

    May block!

  property ident

    Thread identifier of this thread or None if it has not been started.

    This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

  isDaemon()

    Return whether this thread is a daemon.

    This method is deprecated, use the daemon attribute instead.

  is_alive()

    Return whether the thread is alive.

    This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

  join(timeout=None)

    Wait until the thread terminates.

    This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

    When the timeout argument is present and not None, it should be a floating-point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

    When the timeout argument is not present or None, the operation will block until the thread terminates.

    A thread can be join()ed many times.

    join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

  property name

    A string used for identification purposes only.

    It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

  property native_id

    Native integral thread ID of this thread, or None if it has not been started.

    This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

  run()

    Method representing the thread’s activity.

    You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

  setDaemon(daemonic)

    Set whether this thread is a daemon.

    This method is deprecated, use the .daemon property instead.

  setName(name)

    Set the name string for this thread.

    This method is deprecated, use the name attribute instead.

  start()

    Start the thread’s activity.

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the same thread object.

class paramiko.agent.AgentProxyThread(agent)

  Class in charge of communication between two channels.

  property daemon

    A boolean value indicating whether this thread is a daemon thread.

    This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

    The entire Python program exits when only daemon threads are left.

  getName()

    Return a string used for identification purposes only.

    This method is deprecated, use the name attribute instead.

  property ident

    Thread identifier of this thread or None if it has not been started.

    This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

  isDaemon()

    Return whether this thread is a daemon.

    This method is deprecated, use the daemon attribute instead.

  is_alive()

    Return whether the thread is alive.

    This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

  join(timeout=None)

    Wait until the thread terminates.

    This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

    When the timeout argument is present and not None, it should be a floating-point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

    When the timeout argument is not present or None, the operation will block until the thread terminates.

    A thread can be join()ed many times.

    join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

  property name

    A string used for identification purposes only.

    It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

  property native_id

    Native integral thread ID of this thread, or None if it has not been started.

    This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

  run()

    Method representing the thread’s activity.

    You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

  setDaemon(daemonic)

    Set whether this thread is a daemon.

    This method is deprecated, use the .daemon property instead.

  setName(name)

    Set the name string for this thread.

    This method is deprecated, use the name attribute instead.

  start()

    Start the thread’s activity.

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the same thread object.

class paramiko.agent.AgentRemoteProxy(agent, chan)

  Class to be used when wanting to ask a remote SSH Agent

  property daemon

    A boolean value indicating whether this thread is a daemon thread.

    This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

    The entire Python program exits when only daemon threads are left.

  getName()

    Return a string used for identification purposes only.

    This method is deprecated, use the name attribute instead.

  property ident

    Thread identifier of this thread or None if it has not been started.

    This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

  isDaemon()

    Return whether this thread is a daemon.

    This method is deprecated, use the daemon attribute instead.

  is_alive()

    Return whether the thread is alive.

    This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

  join(timeout=None)

    Wait until the thread terminates.

    This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

    When the timeout argument is present and not None, it should be a floating-point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

    When the timeout argument is not present or None, the operation will block until the thread terminates.

    A thread can be join()ed many times.

    join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

  property name

    A string used for identification purposes only.

    It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

  property native_id

    Native integral thread ID of this thread, or None if it has not been started.

    This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

  run()

    Method representing the thread’s activity.

    You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

  setDaemon(daemonic)

    Set whether this thread is a daemon.

    This method is deprecated, use the .daemon property instead.

  setName(name)

    Set the name string for this thread.

    This method is deprecated, use the name attribute instead.

  start()

    Start the thread’s activity.

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the same thread object.

class paramiko.agent.AgentRequestHandler(chanClient)

  Primary/default implementation of SSH agent forwarding functionality.

  Simply instantiate this class, handing it a live command-executing session object, and it will handle forwarding any local SSH agent processes it finds.

  For example:

      # Connect
      client = SSHClient()
      client.connect(host, port, username)
      # Obtain session
      session = client.get_transport().open_session()
      # Forward local agent
      AgentRequestHandler(session)
      # Commands executed after this point will see the forwarded agent on
      # the remote end.
      session.exec_command("git clone https://my.git.repository/")

class paramiko.agent.AgentServerProxy(t)

  Allows an SSH server to access a forwarded agent.

  This also creates a unix domain socket on the system to allow external programs to also access the agent. For this reason, you probably only want to create one of these.

  `connect()` must be called before it is usable. This will also load the list of keys the agent contains. You must also call `close()` in order to clean up the unix socket and the thread that maintains it. (`contextlib.closing` might be helpful to you.)

  Parameters:

    t (.Transport) – Transport used for SSH Agent communication forwarding

  Raises:

    `SSHException` – mostly if we lost the agent

  close()

    Terminate the agent, clean the files, close connections Should be called manually

  get_env()

    Helper for the environment under unix

    Returns:

      a dict containing the `SSH_AUTH_SOCK` environment variables

  get_keys()

    Return the list of keys available through the SSH agent, if any. If no SSH agent was running (or it couldn’t be contacted), an empty list will be returned.

    This method performs no IO, just returns the list of keys retrieved when the connection was made.

    Returns:

      a tuple of `AgentKey` objects representing keys available on the SSH agent

paramiko.agent.get_agent_connection()

  Returns some SSH agent object, or None if none were found/supported.

  New in version 2.10.