# API Documentation

## Overview

The AsyncSSH API is modeled after the new Python `asyncio` framework, with a `create_connection()` coroutine to create an SSH client and a `create_server()` coroutine to create an SSH server. Like the `asyncio` framework, these calls take a parameter of a factory which creates protocol objects to manage the connections once they are open. For AsyncSSH, `create_connection()` should be passed a `client_factory` which returns objects derived from `SSHClient` and `create_server()` should be passed a `server_factory` which returns objects derived from `SSHServer`. In addition, each connection will have an associated `SSHClientConnection` or `SSHServerConnection` object passed to the protocol objects which can be used to perform actions on the connection.

For client connections, authentication can be performed by passing in a username and password or SSH keys as arguments to `create_connection()` or by implementing handler methods on the `SSHClient` object which return credentials when the server requests them. If no credentials are provided, AsyncSSH automatically attempts to send the username of the local user and the keys found in their `.ssh` subdirectory. A list of expected server host keys can also be specified, with AsyncSSH defaulting to looking for matching lines in the user’s `.ssh/known_hosts` file.

For server connections, handlers can be implemented on the `SSHServer` object to return which authentication methods are supported and to validate credentials provided by clients.

Once an SSH client connection is established and authentication is successful, multiple simultaneous channels can be opened on it. This is accomplished calling methods such as `create_session()` or `create_connection()` on the `SSHClientConnection` object. The client can also set up listeners on remote TCP ports by calling `create_server()`. All of these methods take `session_factory` arguments that return `SSHClientSession` or `SSHTCPSession` objects used to manage the channels once they are open. Alternately, channels can be opened using `open_session()` or `open_connection()`, which return `SSHReader` and `SSHWriter` objects which can be used to perform I/O on the channel. The method `start_server()` can be used to set up listeners on remote TCP ports and get back these `SSHReader` and `SSHWriter` objects in a callback when new connections are opened.

The client can also set up TCP port forwarding by calling `forward_local_port()` or `forward_remote_port()`. In these cases, data transfer on the channels is managed automatically by AsyncSSH whenever new connections are opened, so custom session objects are not required.

When an SSH server receives a new connection and authentication is successful, handlers such as `session_requested()`, `connection_requested()`, and `server_requested()` on the associated `SSHServer` object will be called when clients attempt to open channels or set up listeners. These methods return coroutines which can set up the requested sessions or connections, returning `SSHServerSession` or `SSHTCPSession` objects or handler functions that accept `SSHReader` and `SSHWriter` objects as arguments which manage the channels once they are open.

Each session object also has an associated `SSHClientChannel`, `SSHServerChannel`, or `SSHTCPChannel` object passed to it which can be used to perform actions on the channel. These channel objects provide a superset of the functionality found in `asyncio` transport objects.

In addition to the above functions and classes, helper functions for importing public and private keys can be found below under Public Key Support, exceptions can be found under Known hosts, supported algorithms can be found under Supported Algorithms, and some useful constants can be found under Constants.

## Main Functions

### create_connection

`asyncssh.``create_connection`(client_factory, host, port=22, *, loop=None, family=0, flags=0, local_addr=None, known_hosts=(), username=None, client_keys=(), password=None, kex_algs=(), encryption_algs=(), mac_algs=(), compression_algs=(), rekey_bytes=1073741824, rekey_seconds=3600)

  Create an SSH client connection

  This function is a coroutine which can be run to create an outbound SSH client connection to the specified host and port.

  When successful, the following steps occur:

  > 1. The connection is established and an `SSHClientConnection` object is created to represent it.
  > 2. The `client_factory` is called without arguments and should return an `SSHClient` object.
  > 3. The client object is tied to the connection and its `connection_made()` method is called.
  > 4. The SSH handshake and authentication process is initiated, calling methods on the client object if needed.
  > 5. When authentication completes successfully, the client’s `auth_completed()` method is called.
  > 6. The coroutine returns the `(connection, client)` pair. At this point, the connection is ready for sessions to be opened or port forwarding to be set up.

  If an error occurs, it will be raised as an exception and the partially open connection and client objects will be cleaned up.

  Note

  Unlike `socket.create_connection()`, asyncio calls to create a connection do not support a `timeout` parameter. However, asyncio calls can be wrapped in a call to `asyncio.wait_for()` or `asyncio.wait()` which takes a timeout and provides equivalent functionality.

  Parameters:

  - client_factory (callable) – A callable which returns an `SSHClient` object that will be tied to the connection
  - host (string) – The hostname or address to connect to
  - port (integer) – (optional) The port number to connect to. If not specified, the default SSH port is used.
  - loop – (optional) The event loop to use when creating the connection. If not specified, the default event loop is used.
  - family (`socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`) – (optional) The address family to use when creating the socket. By default, the address family is automatically selected based on the host.
  - flags (flags to pass to `getaddrinfo()`) – (optional) The flags to pass to getaddrinfo() when looking up the host address
  - local_addr (tuple of string and integer) – (optional) The host and port to bind the socket to before connecting
  - known_hosts (see Specifying known hosts) – (optional) The list of keys which will be used to validate the server host key presented during the SSH handshake. If this is not specified, the keys will be looked up in the file `.ssh/known_hosts`. If this is explicitly set to `None`, server host key validation will be disabled.
  - username (string) – (optional) Username to authenticate as on the server. If not specified, the currently logged in user on the local machine will be used.
  - client_keys (see Specifying private keys) – (optional) A list of keys which will be used to authenticate this client via public key authentication. If no client keys are specified, an attempt will be made to load them from the files `.ssh/id_ed25519`, `.ssh/id_ecdsa`, `.ssh/id_rsa`, and `.ssh/id_dsa`, with optional certificates loaded from the files `.ssh/id_ed25519-cert.pub`, `.ssh/id_ecdsa-cert.pub`, `.ssh/id_rsa-cert.pub`, and `.ssh/id_dsa-cert.pub`. If this argument is explicitly set to `None`, client public key authentication will not be performed.
  - password (string) – (optional) The password to use for client password authentication or keyboard-interactive authentication which prompts for a password. If this is not specified, client password authentication will not be performed.
  - kex_algs (list of strings) – (optional) A list of allowed key exchange algorithms in the SSH handshake, taken from key exchange algorithms
  - encryption_algs (list of strings) – (optional) A list of encryption algorithms to use during the SSH handshake, taken from encryption algorithms
  - mac_algs (list of strings) – (optional) A list of MAC algorithms to use during the SSH handshake, taken from MAC algorithms
  - compression_algs (list of strings) – (optional) A list of compression algorithms to use during the SSH handshake, taken from compression algorithms, or `None` to disable compression
  - rekey_bytes (integer) – (optional) The number of bytes which can be sent before the SSH session key is renegotiated. This defaults to 1 GB.
  - rekey_seconds (integer) – (optional) The maximum time in seconds before the SSH session key is renegotiated. This defaults to 1 hour.

  Returns: | An `SSHClientConnection` and `SSHClient`

### create_server

`asyncssh.``create_server`(server_factory, host=None, port=22, *, loop=None, family=0, flags=1, backlog=100, reuse_address=None, server_host_keys, authorized_client_keys=None, kex_algs=(), encryption_algs=(), mac_algs=(), compression_algs=(), allow_pty=True, session_factory=None, session_encoding='utf-8', sftp_factory=None, window=2097152, max_pktsize=32768, rekey_bytes=1073741824, rekey_seconds=3600)

  Create an SSH server

  This function is a coroutine which can be run to create an SSH server bound to the specified host and port. The return value is an `AbstractServer` object which can be used later to shut down the server.

  Parameters:

  - server_factory (callable) – A callable which returns an `SSHServer` object that will be created for each new inbound connection
  - host (string) – (optional) The hostname or address to listen on. If not specified, listeners are created for all addresses.
  - port (integer) – (optional) The port number to listen on. If not specified, the default SSH port is used.
  - loop – (optional) The event loop to use when creating the server. If not specified, the default event loop is used.
  - family (`socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`) – (optional) The address family to use when creating the server. By default, the address families are automatically selected based on the host.
  - flags (flags to pass to `getaddrinfo()`) – (optional) The flags to pass to getaddrinfo() when looking up the host
  - backlog (integer) – (optional) The maximum number of queued connections allowed on listeners
  - reuse_address (boolean) – (optional) Whether or not to reuse a local socket in the TIME_WAIT state without waiting for its natural timeout to expire. If not specified, this will be automatically set to `True` on UNIX.
  - server_host_keys (see Specifying private keys) – A list of private keys and optional certificates which can be used by the server as a host key. This argument must be specified.
  - authorized_client_keys (see Specifying authorized keys) – (optional) A list of authorized user and CA public keys which should be trusted for certifcate-based client public key authentication.
  - kex_algs (list of strings) – (optional) A list of allowed key exchange algorithms in the SSH handshake, taken from key exchange algorithms
  - encryption_algs (list of strings) – (optional) A list of encryption algorithms to use during the SSH handshake, taken from encryption algorithms
  - mac_algs (list of strings) – (optional) A list of MAC algorithms to use during the SSH handshake, taken from MAC algorithms
  - compression_algs (list of strings) – (optional) A list of compression algorithms to use during the SSH handshake, taken from compression algorithms, or `None` to disable compression
  - allow_pty (boolean) – (optional) Whether or not to allow allocation of a pseudo-tty in sessions, defaulting to `True`
  - session_factory (callable) – (optional) A callable or coroutine handler function which takes AsyncSSH stream objects for stdin, stdout, and stderr that will be called each time a new shell, exec, or subsytem other than SFTP is requested by the client. If not specified, sessions are rejected by default unless the `session_requested()` method is overridden on the `SSHServer` object returned by `server_factory` to make this decision.
  - session_encoding (string) – (optional) The Unicode encoding to use for data exchanged on sessions on this server, defaulting to UTF-8 (ISO 10646) format. If `None` is passed in, the application can send and receive raw bytes.
  - sftp_factory (callable) – (optional) A callable which returns an `SFTPServer` object that will be created each time an SFTP session is requested by the client, or `True` to use the base `SFTPServer` class to handle SFTP requests. If not specified, SFTP sessions are rejected by default.
  - window (integer) – (optional) The receive window size for sessions on this server
  - max_pktsize (integer) – (optional) The maximum packet size for sessions on this server
  - rekey_bytes (integer) – (optional) The number of bytes which can be sent before the SSH session key is renegotiated, defaulting to 1 GB
  - rekey_seconds (integer) – (optional) The maximum time in seconds before the SSH session key is renegotiated, defaulting to 1 hour

  Returns: | `AbstractServer`

### connect

`asyncssh.``connect`(host, port=22, **kwargs)

  Make an SSH client connection

  This function is a coroutine wrapper around `create_connection()` which can be used when a custom SSHClient instance is not needed. It takes all the same arguments as `create_connection()` except for `client_factory` and returns only the `SSHClientConnection` object rather than a tuple of an `SSHClientConnection` and `SSHClient`.

  When using this call, the following restrictions apply:

  > 1. No callbacks are called when the connection is successfully opened, when it is closed, or when authentication completes.
  > 2. Any authentication information must be provided as arguments to this call, as any authentication callbacks will deny other authentication attempts. Also, authentication banner information will be ignored.
  > 3. Any debug messages sent by the server will be ignored.

### listen

`asyncssh.``listen`(host, port=22, *, server_host_keys, **kwargs)

  Start an SSH server

  This function is a coroutine wrapper around `create_server()` which can be used when a custom SSHServer instance is not needed. It takes all the same arguments as `create_server()` except for `server_factory`.

  When using this call, the following restrictions apply:

  > 1. No callbacks are called when a new connection arrives, when a connection is closed, or when authentication completes.
  > 2. Any authentication information must be provided as arguments to this call, as any authentication callbacks will deny other authentication attempts. Currently, this allows only public key authentication to be used, by passing in the `authorized_client_keys` argument.
  > 3. Only handlers using the streams API are supported and the same handlers must be used for all clients. These handlers must be provided in the `session_factory` and/or `sftp_factory` arguments to this call.
  > 4. Any debug messages sent by the client will be ignored.

## Main Classes

### SSHClient

class `asyncssh.``SSHClient`

  SSH client protocol handler

  Applications should subclass this when implementing an SSH client. The functions listed below should be overridden to define application-specific behavior. In particular, the method `auth_completed()` should be defined to open the desired SSH channels on this connection once authentication has been completed.

  For simple password or public key based authentication, nothing needs to be defined here if the password or client keys are passed in when the connection is created. However, to prompt interactively or otherwise dynamically select these values, the methods `password_auth_requested()` and/or `public_key_auth_requested()` can be defined. Keyboard-interactive authentication is also supported via `kbdint_auth_requested()` and `kbdint_challenge_received()`.

  If the server sends an authentication banner, the method `auth_banner_received()` will be called.

  If the server requires a password change, the method `password_change_requested()` will be called, followed by either `password_changed()` or `password_change_failed()` depending on whether the password change is successful.

  General connection handlers |
  --- | ---

  `connection_made`(connection)

    Called when a connection is made

    This method is called as soon as the TCP connection completes. The connection parameter should be stored if needed for later use.

    Parameters: | connection (`SSHClientConnection`) – The connection which was successfully opened

  `connection_lost`(exc)

    Called when a connection is lost or closed

    This method is called when a connection is closed. If the connection is shut down cleanly, exc will be `None`. Otherwise, it will be an exception explaining the reason for the disconnect.

    Parameters: | exc (`Exception`) – The exception which caused the connection to close, or `None` if the connection closed cleanly

  `debug_msg_received`(msg, lang, always_display)

    A debug message was received on this connection

    This method is called when the other end of the connection sends a debug message. Applications should implement this method if they wish to process these debug messages.

    Parameters:

    - msg (string) – The debug message sent
    - lang (string) – The language the message is in
    - always_display (boolean) – Whether or not to display the message

  General authentication handlers |
  --- | ---

  `auth_banner_received`(msg, lang)

    An incoming authentication banner was received

    This method is called when the server sends a banner to display during authentication. Applications should implement this method if they wish to do something with the banner.

    Parameters:

    - msg (string) – The message the server wanted to display
    - lang (string) – The language the message is in

  `auth_completed`()

    Authentication was completed successfully

    This method is called when authentication has completed succesfully. Applications may use this method to create whatever client sessions and direct TCP/IP connections are needed and/or set up listeners for incoming TCP/IP connections coming from the server.

  Public key authentication handlers |
  --- | ---

  `public_key_auth_requested`()

    Public key authentication has been requested

    This method should return a private key corresponding to the user that authentication is being attempted for.

    This method may be called multiple times and can return a different key to try each time it is called. When there are no keys left to try, it should return `None` to indicate that some other authentication method should be tried.

    If client keys were provided when the connection was opened, they will be tried before this method is called.

    If blocking operations need to be performed to determine the key to authenticate with, this method may be defined as a coroutine.

    Returns: | A key as described in Specifying private keys or `None` to move on to another authentication method

  Password authentication handlers |
  --- | ---

  `password_auth_requested`()

    Password authentication has been requested

    This method should return a string containing the password corresponding to the user that authentication is being attempted for. It may be called multiple times and can return a different password to try each time, but most servers have a limit on the number of attempts allowed. When there’s no password left to try, this method should return `None` to indicate that some other authentication method should be tried.

    If a password was provided when the connection was opened, it will be tried before this method is called.

    If blocking operations need to be performed to determine the password to authenticate with, this method may be defined as a coroutine.

    Returns: | A string containing the password to authenticate with or `None` to move on to another authentication method

  `password_change_requested`(prompt, lang)

    A password change has been requested

    This method is called when password authentication was attempted and the user’s password was expired on the server. To request a password change, this method should return a tuple or two strings containing the old and new passwords. Otherwise, it should return `NotImplemented`.

    If blocking operations need to be performed to determine the passwords to authenticate with, this method may be defined as a coroutine.

    By default, this method returns `NotImplemented`.

    Parameters:

    - prompt (string) – The prompt requesting that the user enter a new password
    - lang (string) – the language that the prompt is in

    Returns: | A tuple of two strings containing the old and new passwords or `NotImplemented` if password changes aren’t supported

  `password_changed`()

    The requested password change was successful

    This method is called to indicate that a requested password change was successful. It is generally followed by a call to `auth_completed()` since this means authentication was also successful.

  `password_change_failed`()

    The requested password change has failed

    This method is called to indicate that a requested password change failed, generally because the requested new password doesn’t meet the password criteria on the remote system. After this method is called, other forms of authentication will automatically be attempted.

  Keyboard-interactive authentication handlers |
  --- | ---

  `kbdint_auth_requested`()

    Keyboard-interactive authentication has been requested

    This method should return a string containing a comma-separated list of submethods that the server should use for keyboard-interactive authentication. An empty string can be returned to let the server pick the type of keyboard-interactive authentication to perform. If keyboard-interactive authentication is not supported, `None` should be returned.

    By default, keyboard-interactive authentication is supported if a password was provided when the `SSHClient` was created and it hasn’t been sent yet. If the challenge is not a password challenge, this authentication will fail. This method and the `kbdint_challenge_received()` method can be overridden if other forms of challenge should be supported.

    If blocking operations need to be performed to determine the submethods to request, this method may be defined as a coroutine.

    Returns: | A string containing the submethods the server should use for authentication or `None` to move on to another authentication method

  `kbdint_challenge_received`(name, instruction, lang, prompts)

    A keyboard-interactive auth challenge has been received

    This method is called when the server sends a keyboard-interactive authentication challenge.

    The return value should be a list of strings of the same length as the number of prompts provided if the challenge can be answered, or `None` to indicate that some other form of authentication should be attempted.

    If blocking operations need to be performed to determine the responses to authenticate with, this method may be defined as a coroutine.

    By default, this method will look for a challenge consisting of a single ‘Password:’ prompt, and call the method `password_auth_requested()` to provide the response. It will also ignore challenges with no prompts (generally used to provide instructions). Any other form of challenge will cause this method to return `None` to move on to another authentication method.

    Parameters:

    - name (string) – The name of the challenge
    - instruction (string) – Instructions to the user about how to respond to the challenge
    - lang (string) – The language the challenge is in
    - prompts (list of tuples of string and boolean) – The challenges the user should respond to and whether or not the responses should be echoed when they are entered

    Returns: | List of string responses to the challenge or `None` to move on to another authentication method

### SSHServer

class `asyncssh.``SSHServer`

  SSH server protocol handler

  Applications should subclass this when implementing an SSH server. At a minimum, one or more of the authentication handlers will need to be overridden to perform authentication, or `begin_auth()` should be overridden to return `False` to indicate that no authentication is required.

  In addition, one or more of the `session_requested()`, `connection_requested()`, or `server_requested()` methods will need to be overridden to handle requests to open sessions or direct TCP/IP connections or set up listeners for forwarded TCP/IP connections.

  General connection handlers |
  --- | ---

  `connection_made`(connection)

    Called when a connection is made

    This method is called when a new TCP connection is accepted. The connection parameter should be stored if needed for later use.

  `connection_lost`(exc)

    Called when a connection is lost or closed

    This method is called when a connection is closed. If the connection is shut down cleanly, exc will be `None`. Otherwise, it will be an exception explaining the reason for the disconnect.

  `debug_msg_received`(msg, lang, always_display)

    A debug message was received on this connection

    This method is called when the other end of the connection sends a debug message. Applications should implement this method if they wish to process these debug messages.

    Parameters:

    - msg (string) – The debug message sent
    - lang (string) – The language the message is in
    - always_display (boolean) – Whether or not to display the message

  General authentication handlers |
  --- | ---

  `begin_auth`(username)

    Authentication has been requested by the client

    This method will be called when authentication is attempted for the specified user. Applications should use this method to prepare whatever state they need to complete the authentication, such as loading in the set of authorized keys for that user. If no authentication is required for this user, this method should return `False` to cause the authentication to immediately succeed. Otherwise, it should return `True` to indicate that authentication should proceed.

    Parameters: | username (string) – The name of the user being authenticated
    Returns: | A boolean indicating whether authentication is required

  Public key authentication handlers |
  --- | ---

  `public_key_auth_supported`()

    Return whether or not public key authentication is supported

    This method should return `True` if client public key authentication is supported. Applications wishing to support it must have this method return `True` and implement `validate_public_key()` to return whether or not the key provided by the client is valid for the user being authenticated.

    By default, it returns `False` indicating the client public key authentication is not supported.

    Returns: | A boolean indicating if public key authentication is supported or not

  `validate_public_key`(username, key)

    Return whether key is an authorized client key for this user

    Basic key-based client authentication can be supported by passing authorized keys in the `authorized_client_keys` argument of `create_server()`, or by calling `set_authorized_keys` on the server connection from the `begin_auth()` method. However, for more flexibility in matching on the allowed set of keys, this method can be implemented by the application to do the matching itself. It should return `True` if the specified key is a valid client key for the user being authenticated.

    This method may be called multiple times with different keys provided by the client. Applications should precompute as much as possible in the `begin_auth()` method so that this function can quickly return whether the key provided is in the list.

    If blocking operations need to be performed to determine the validity of the key, this method may be defined as a coroutine.

    By default, this method returns `False` for all client keys.

    > Note

    > This function only needs to report whether the public key provided is a valid client key for this user. If it is, AsyncSSH will verify that the client possesses the corresponding private key before allowing the authentication to succeed.

    Parameters:

    - username (string) – The user being authenticated
    - key (`SSHKey` public key) – The public key sent by the client

    Returns: | A boolean indicating if the specified key is a valid client key for the user being authenticated

  `validate_ca_key`(username, key)

    Return whether key is an authorized CA key for this user

    Basic key-based client authentication can be supported by passing authorized keys in the `authorized_client_keys` argument of `create_server()`, or by calling `set_authorized_keys` on the server connection from the `begin_auth()` method. However, for more flexibility in matching on the allowed set of keys, this method can be implemented by the application to do the matching itself. It should return `True` if the specified key is a valid certificate authority key for the user being authenticated.

    This method may be called multiple times with different keys provided by the client. Applications should precompute as much as possible in the `begin_auth()` method so that this function can quickly return whether the key provided is in the list.

    If blocking operations need to be performed to determine the validity of the key, this method may be defined as a coroutine.

    By default, this method returns `False` for all CA keys.

    > Note

    > This function only needs to report whether the public key provided is a valid CA key for this user. If it is, AsyncSSH will verify that the certificate is valid, that the user is one of the valid principals for the certificate, and that the client possesses the private key corresponding to the public key in the certificate before allowing the authentication to succeed.

    Parameters:

    - username (string) – The user being authenticated
    - key (`SSHKey` public key) – The public key which signed the certificate sent by the client

    Returns: | A boolean indicating if the specified key is a valid CA key for the user being authenticated

  Password authentication handlers |
  --- | ---

  `password_auth_supported`()

    Return whether or not password authentication is supported

    This method should return `True` if password authentication is supported. Applications wishing to support it must have this method return `True` and implement `validate_password()` to return whether or not the password provided by the client is valid for the user being authenticated.

    By default, this method returns `False` indicating that password authentication is not supported.

    Returns: | A boolean indicating if password authentication is supported or not

  `validate_password`(username, password)

    Return whether password is valid for this user

    This method should return `True` if the specified password is a valid password for the user being authenticated. It must be overridden by applications wishing to support password authentication.

    This method may be called multiple times with different passwords provided by the client. Applications may wish to limit the number of attempts which are allowed. This can be done by having `password_auth_supported()` begin returning `False` after the maximum number of attempts is exceeded.

    If blocking operations need to be performed to determine the validity of the password, this method may be defined as a coroutine.

    By default, this method returns `False` for all passwords.

    Parameters:

    - username (string) – The user being authenticated
    - password (string) – The password sent by the client

    Returns: | A boolean indicating if the specified password is valid for the user being authenticated

  Keyboard-interactive authentication handlers |
  --- | ---

  `kbdint_auth_supported`()

    Return whether or not keyboard-interactive authentication is supported

    This method should return `True` if keyboard-interactive authentication is supported. Applications wishing to support it must have this method return `True` and implement `get_kbdint_challenge()` and `validate_kbdint_response()` to generate the apporiate challenges and validate the responses for the user being authenticated.

    Returns: | A boolean indicating if keyboard-interactive authentication is supported or not

  `get_kbdint_challenge`(username, lang, submethods)

    Return a keyboard-interactive auth challenge

    This method should return `True` if authentication should succeed without any challenge, `False` if authentication should fail without any challenge, or an auth challenge consisting of a challenge name, instructions, a language tag, and a list of tuples containing prompt strings and booleans indicating whether input should be echoed when a value is entered for that prompt.

    If blocking operations need to be performed to determine the challenge to issue, this method may be defined as a coroutine.

    Parameters:

    - username (string) – The user being authenticated
    - lang (string) – The language requested by the client for the challenge
    - submethods (string) – A comma-separated list of the types of challenges the client can support, or the empty string if the server should choose

    Returns: | An authentication challenge as described above

  `validate_kbdint_response`(username, responses)

    Return whether the keyboard-interactive response is valid for this user

    This method should validate the keyboard-interactive responses provided and return `True` if authentication should succeed with no further challenge, `False` if authentication should fail, or an additional auth challenge in the same format returned by `get_kbdint_challenge()`. Any series of challenges can be returned this way. To print a message in the middle of a sequence of challenges without prompting for additional data, a challenge can be returned with an empty list of prompts. After the client acknowledges this message, this function will be called again with an empty list of responses to continue the authentication.

    If blocking operations need to be performed to determine the validity of the response or the next challenge to issue, this method may be defined as a coroutine.

    Parameters:

    - username (string) – The user being authenticated
    - responses (list of strings) – A list of responses to the last challenge

    Returns: | `True`, `False`, or the next challenge

  Channel session open handlers |
  --- | ---

  `session_requested`()

    Handle an incoming session request

    This method is called when a session open request is received from the client, indicating it wishes to open a channel to be used for running a shell, executing a command, or connecting to a subsystem. If the application wishes to accept the session, it must override this method to return either an `SSHServerSession` object to use to process the data received on the channel or a tuple consisting of an `SSHServerChannel` object created with `create_server_channel` and an `SSHServerSession`, if the application wishes to pass non-default arguments when creating the channel.

    If blocking operations need to be performed before the session can be created, a coroutine which returns an `SSHServerSession` object can be returned instead of the session iself. This can be either returned directly or as a part of a tuple with an `SSHServerChannel` object.

    To reject this request, this method should return `False` to send back a “Session refused” response or raise a `ChannelOpenError` exception with the reason for the failure.

    The details of what type of session the client wants to start will be delivered to methods on the `SSHServerSession` object which is returned, along with other information such as environment variables, terminal type, size, and modes.

    By default, all session requests are rejected.

    Returns:

    One of the following:
    - An `SSHServerSession` object or a coroutine which returns an `SSHServerSession`
    - A tuple consisting of an `SSHServerChannel` and the above
    - A callable or coroutine handler function which takes AsyncSSH stream objects for stdin, stdout, and stderr as arguments
    - A tuple consisting of an `SSHServerChannel` and the above
    - `False` to refuse the request

    Raises: | `ChannelOpenError` if the session shouldn’t be accepted

  `connection_requested`(dest_host, dest_port, orig_host, orig_port)

    Handle a direct TCP/IP connection request

    This method is called when a direct TCP/IP connection request is received by the server. Applications wishing to accept such connections must override this method.

    To allow standard port forwarding of data on the connection to the requested destination host and port, this method should return `True`.

    To reject this request, this method should return `False` to send back a “Connection refused” response or raise an `ChannelOpenError` exception with the reason for the failure.

    If the application wishes to process the data on the connection itself, this method should return either an `SSHTCPSession` object which can be used to process the data received on the channel or a tuple consisting of of an `SSHTCPChannel` object created with `create_tcp_channel()` and an `SSHTCPSession`, if the application wishes to pass non-default arguments when creating the channel.

    If blocking operations need to be performed before the session can be created, a coroutine which returns an `SSHTCPSession` object can be returned instead of the session iself. This can be either returned directly or as a part of a tuple with an `SSHTCPChannel` object.

    By default, all connection requests are rejected.

    Parameters:

    - dest_host (string) – The address the client wishes to connect to
    - dest_port (integer) – The port the client wishes to connect to
    - orig_host (string) – The address the connection was originated from
    - orig_port (integer) – The port the connection was originated from

    Returns:

    One of the following:
    - An `SSHTCPSession` object or a coroutine which returns an `SSHTCPSession`
    - A tuple consisting of an `SSHTCPChannel` and the above
    - A callable or coroutine handler function which takes AsyncSSH stream objects for reading and writing to the connection
    - A tuple consisting of an `SSHTCPChannel` and the above
    - `True` to request standard port forwarding
    - `False` to refuse the connection

    Raises: | `ChannelOpenError` if the connection shouldn’t be accepted

  `server_requested`(listen_host, listen_port)

    Handle a request to listen on a TCP/IP address and port

    This method is called when a client makes a request to listen on an address and port for incoming TCP connections. The port to listen on may be `0` to request a dynamically allocated port. Applications wishing to allow TCP/IP connection forwarding must override this method.

    To set up standard port forwarding of connections received on this address and port, this method should return `True`.

    If the application wishes to manage listening for incoming connections itself, this method should return an `SSHListener` object that listens for new connections and calls `create_connection` on each of them to forward them back to the client or returns `None` if the listener can’t be set up.

    If blocking operations need to be performed to set up the listener, a coroutine which returns an `SSHListener` can be returned instead of the listener itself.

    To reject this request, this method should return `False`.

    By default, this method rejects all server requests.

    Parameters:

    - listen_host (string) – The address the server should listen on
    - listen_port (integer) – The port the server should listen on, or the value `0` to request that the server dynamically allocate a port

    Returns:

    One of the following:
    - An `SSHListener` object or a coroutine which returns an `SSHListener` or `False` if the listener can’t be opened
    - `True` to set up standard port forwarding
    - `False` to reject the request

## Connection Classes

### SSHClientConnection

class `asyncssh.``SSHClientConnection`

  SSH client connection

  This class represents an SSH client connection.

  Once authentication is successful on a connection, new client sessions can be opened by calling `create_session()`.

  Direct TCP connections can be opened by calling `create_connection()`.

  Remote listeners for forwarded TCP connections can be opened by calling `create_server()`.

  TCP port forwarding can be set up by calling `forward_local_port()` or `forward_remote_port()`.

  General connection methods |
  --- | ---

  `get_extra_info`(name, default=None)

    Get additional information about the connection

    This method returns extra information about the connection once it is established. Supported values include everything supported by a socket transport plus:

    > username
    > client_version
    > server_version
    > send_cipher
    > send_mac
    > send_compression
    > recv_cipher
    > recv_mac
    > recv_compression

    See `get_extra_info()` in `asyncio.BaseTransport` for more information.

  `send_debug`(msg, lang='en-US', always_display=False)

    Send a debug message on this connection

    This method can be called to send a debug message to the other end of the connection.

    Parameters:

    - msg (string) – The debug message to send
    - lang (string) – The language the message is in
    - always_display (boolean) – Whether or not to display the message

  Client session open methods |
  --- | ---

  `create_session`(session_factory, command=None, *, subsystem=None, env={}, term_type=None, term_size=None, term_modes={}, encoding='utf-8', window=2097152, max_pktsize=32768)

    Create an SSH client session

    This method is a coroutine which can be called to create an SSH client session used to execute a command, start a subsystem such as sftp, or if no command or subsystem is specific run an interactive shell. Optional arguments allow terminal and environment information to be provided.

    By default, this class expects string data in its send and receive functions, which it encodes on the SSH connection in UTF-8 (ISO 10646) format. An optional encoding argument can be passed in to select a different encoding, or `None` can be passed in if the application wishes to send and receive raw bytes.

    Other optional arguments include the SSH receive window size and max packet size which default to 2 MB and 32 KB, respectively.

    Parameters:

    - session_factory (callable) – A callable which returns an `SSHClientSession` object that will be created to handle activity on this session
    - command (string) – (optional) The remote command to execute. By default, an interactive shell is started if no command or subsystem is provided.
    - subsystem (string) – (optional) The name of a remote subsystem to start up
    - env (dictionary) –

      (optional) The set of environment variables to set for this session. Keys and values passed in here will be converted to Unicode strings encoded as UTF-8 (ISO 10646) for transmission.

      Note

      Many SSH servers restrict which environment variables a client is allowed to set. The server’s configuration may need to be edited before environment variables can be successfully set in the remote environment.

    - term_type (string) – (optional) The terminal type to set for this session. If this is not set, a pseudo-terminal will not be requested for this session.
    - term_size (tuple of 2 or 4 integers) – (optional) The terminal width and height in characters and optionally the width and height in pixels
    - term_modes – (optional) POSIX terminal modes to set for this session, where keys are taken from POSIX terminal modes with values defined in section 8 of RFC 4254#section-8.
    - encoding (string) – (optional) The Unicode encoding to use for data exchanged on the connection
    - window (integer) – (optional) The receive window size for this session
    - max_pktsize (integer) – (optional) The maximum packet size for this session

    Returns: | an `SSHClientChannel` and `SSHClientSession`

  `open_session`(*args, **kwargs)

    Open an SSH client session

    This method is a coroutine wrapper around `create_session()` designed to provide a “high-level” stream interface for creating an SSH client session. Instead of taking a `session_factory` argument for constructing an object which will handle activity on the session via callbacks, it returns an `SSHWriter` and two `SSHReader` objects representing stdin, stdout, and stderr which can be used to perform I/O on the session. With the exception of `session_factory`, all of the arguments to `create_session()` are supported and have the same meaning.

  `create_connection`(session_factory, dest_host, dest_port, orig_host='', orig_port=0, *, encoding=None, window=2097152, max_pktsize=32768)

    Create an SSH TCP direct connection

    This method is a coroutine which can be called to request that the server open a new outbound TCP connection to the specified destination host and port. If the connection is successfully opened, a new SSH channel will be opened with data being handled by a `SSHTCPSession` object created by `session_factory`.

    Optional arguments include the host and port of the original client opening the connection when performing TCP port forwarding.

    By default, this class expects data to be sent and received as raw bytes. However, an optional encoding argument can be passed in to select the encoding to use, allowing the application send and receive string data.

    Other optional arguments include the SSH receive window size and max packet size which default to 2 MB and 32 KB, respectively.

    Parameters:

    - session_factory (callable) – A callable which returns an `SSHClientSession` object that will be created to handle activity on this session
    - dest_host (string) – The hostname or address to connect to
    - dest_port (integer) – The port number to connect to
    - orig_host (string) – (optional) The hostname or address of the client requesting the connection
    - orig_port (integer) – (optional) The port number of the client requesting the connection
    - encoding (string) – (optional) The Unicode encoding to use for data exchanged on the connection
    - window (integer) – (optional) The receive window size for this session
    - max_pktsize (integer) – (optional) The maximum packet size for this session

    Returns: | an `SSHTCPChannel` and `SSHTCPSession`
    Raises: | `ChannelOpenError` if the connection can’t be opened

  `open_connection`(*args, **kwargs)

    Open an SSH TCP direct connection

    This method is a coroutine wrapper around `create_connection()` designed to provide a “high-level” stream interface for creating an SSH TCP direct connection. Instead of taking a `session_factory` argument for constructing an object which will handle activity on the session via callbacks, it returns `SSHReader` and `SSHWriter` objects which can be used to perform I/O on the connection.

    With the exception of `session_factory`, all of the arguments to `create_connection()` are supported and have the same meaning here.

    Returns: | an `SSHReader` and `SSHWriter`
    Raises: | `ChannelOpenError` if the connection can’t be opened

  `create_server`(session_factory, listen_host, listen_port, *, encoding=None, window=2097152, max_pktsize=32768)

    Create a remote SSH TCP listener

    This method is a coroutine which can be called to request that the server listen on the specified remote address and port for incoming TCP connections. If the request is successful, the return value is an `SSHListener` object which can be used later to shut down the listener. If the request fails, `None` is returned.

    Parameters:

    - session_factory (callable or coroutine) – A callable or coroutine which takes arguments of the original host and port of the client and decides whether to accept the connection or not, either returning an `SSHTCPSession` object used to handle activity on that connection or raising `ChannelOpenError` to indicate that the connection should not be accepted
    - listen_host (string) – The hostname or address on the remote host to listen on
    - listen_port (integer) – The port number on the remote host to listen on
    - encoding (string) – (optional) The Unicode encoding to use for data exchanged on the connection
    - window (integer) – (optional) The receive window size for this session
    - max_pktsize (integer) – (optional) The maximum packet size for this session

    Returns: | `SSHListener` or `None` if the listener can’t be opened

  `start_server`(handler_factory, *args, **kwargs)

    Start a remote SSH TCP listener

    This method is a coroutine wrapper around `create_server()` designed to provide a “high-level” stream interface for creating remote SSH TCP listeners. Instead of taking a `session_factory` argument for constructing an object which will handle activity on the session via callbacks, it takes a `handler_factory` which returns a callable or coroutine that will be passed `SSHReader` and `SSHWriter` objects which can be used to perform I/O on each new connection which arrives. Like `create_server()`, `handler_factory` can also raise `ChannelOpenError` if the connection should not be accepted.

    With the exception of `handler_factory` replacing `session_factory`, all of the arguments to `create_server()` are supported and have the same meaning here.

    Parameters: | handler_factory (callable or coroutine) – A callable or coroutine which takes arguments of the original host and port of the client and decides whether to accept the connection or not, either returning a callback or coroutine used to handle activity on that connection or raising `ChannelOpenError` to indicate that the connection should not be accepted
    Returns: | `SSHListener` or `None` if the listener can’t be opened

  `start_sftp_client`(path_encoding='utf-8', path_errors='strict')

    Start an SFTP client

    This method is a coroutine which attempts to start a secure file transfer session. If it succeeds, it returns an `SFTPClient` object which can be used to copy and access files on the remote host.

    An optional Unicode encoding can be specified for sending and receiving pathnames, defaulting to UTF-8 with strict error checking. If an encoding of `None` is specified, pathnames will be left as bytes rather than being converted to & from strings.

    Parameters:

    - path_encoding (string) – The Unicode encoding to apply when sending and receiving remote pathnames
    - path_errors (string) – The error handling strategy to apply on encode/decode errors

    Returns: | `SFTPClient`
    Raises: | `SFTPError` if the session can’t be opened

  Client forwarding methods |
  --- | ---

  `forward_connection`(dest_host, dest_port)

    Forward a tunneled SSH connection

    This method is a coroutine which can be returned by a `session_factory` to forward connections tunneled over SSH to the specified destination host and port.

    Parameters:

    - dest_host (string) – The hostname or address to forward the connections to
    - dest_port (integer) – The port number to forward the connections to

    Returns: | coroutine that returns an `SSHTCPSession`

  `forward_local_port`(listen_host, listen_port, dest_host, dest_port)

    Set up local port forwarding

    This method is a coroutine which attempts to set up port forwarding from a local listening port to a remote host and port via the SSH connection. If the request is successful, the return value is an `SSHListener` object which can be used later to shut down the port forwarding.

    Parameters:

    - listen_host (string) – The hostname or address on the local host to listen on
    - listen_port (integer) – The port number on the local host to listen on
    - dest_host (string) – The hostname or address to forward the connections to
    - dest_port (integer) – The port number to forward the connections to

    Returns: | `SSHListener`
    Raises: | `OSError` if the listener can’t be opened

  `forward_remote_port`(listen_host, listen_port, dest_host, dest_port)

    Set up remote port forwarding

    This method is a coroutine which attempts to set up port forwarding from a remote listening port to a local host and port via the SSH connection. If the request is successful, the return value is an `SSHListener` object which can be used later to shut down the port forwarding. If the request fails, `None` is returned.

    Parameters:

    - listen_host (string) – The hostname or address on the remote host to listen on
    - listen_port (integer) – The port number on the remote host to listen on
    - dest_host (string) – The hostname or address to forward connections to
    - dest_port (integer) – The port number to forward connections to

    Returns: | `SSHListener` or `None` if the listener can’t be opened

  Connection close methods |
  --- | ---

  `abort`()

    Forcibly close the SSH connection

    This method closes the SSH connection immediately, without waiting for pending operations to complete and wihtout sending an explicit SSH disconnect message. Buffered data waiting to be sent will be lost and no more data will be received. When the the connection is closed, `connection_lost()` on the associated `SSHClient` object will be called with the value `None`.

  `close`()

    Cleanly close the SSH connection

    This method calls `disconnect()` with the reason set to indicate that the connection was closed explicitly by the application.

  `disconnect`(code, reason, lang='en-US')

    Disconnect the SSH connection

    This method sends a disconnect message and closes the SSH connection after buffered data waiting to be written has been sent. No more data will be received. When the connection is fully closed, `connection_lost()` on the associated `SSHClient` or `SSHServer` object will be called with the value `None`.

    Parameters:

    - code (integer) – The reason for the disconnect, from disconnect reason codes
    - reason (string) – A human readable reason for the disconnect
    - lang (string) – The language the reason is in

### SSHServerConnection

class `asyncssh.``SSHServerConnection`

  SSH server connection

  This class represents an SSH server connection.

  During authentication, `send_auth_banner()` can be called to send an authentication banner to the client.

  Once authenticated, `SSHServer` objects wishing to create session objects with non-default channel properties can call `create_server_channel()` from their `session_requested()` method and return a tuple of the `SSHServerChannel` object returned from that and either an `SSHServerSession` object or a coroutine which returns an `SSHServerSession`.

  Similarly, `SSHServer` objects wishing to create TCP connection objects with non-default channel properties can call `create_tcp_channel()` from their `connection_requested()` method and return a tuple of the `SSHTCPChannel` object returned from that and either an `SSHTCPSession` object or a coroutine which returns an `SSHTCPSession`.

  General connection methods |
  --- | ---

  `get_extra_info`(name, default=None)

    Get additional information about the connection

    This method returns extra information about the connection once it is established. Supported values include everything supported by a socket transport plus:

    > username
    > client_version
    > server_version
    > send_cipher
    > send_mac
    > send_compression
    > recv_cipher
    > recv_mac
    > recv_compression

    See `get_extra_info()` in `asyncio.BaseTransport` for more information.

  `send_debug`(msg, lang='en-US', always_display=False)

    Send a debug message on this connection

    This method can be called to send a debug message to the other end of the connection.

    Parameters:

    - msg (string) – The debug message to send
    - lang (string) – The language the message is in
    - always_display (boolean) – Whether or not to display the message

  Server authentication methods |
  --- | ---

  `send_auth_banner`(msg, lang='en-US')

    Send an authentication banner to the client

    This method can be called to send an authentication banner to the client, displaying information while authentication is in progress. It is an error to call this method after the authentication is complete.

    Parameters:

    - msg (string) – The message to display
    - lang (string) – The language the message is in

    Raises: | `OSError` if authentication is already completed

  `set_authorized_keys`(authorized_keys)

    Set the keys trusted for client public key authentication

    This method can be called to set the trusted user and CA keys for client public key authentication. It should generally be called from the `begin_auth` method of `SSHServer` to set the appropriate keys for the user attempting to authenticate.

    Parameters: | authorized_keys (see Specifying authorized keys) – The keys to trust for client public key authentication

  `get_key_option`(option, default=None)

    Return option from authorized_keys

    If a client key or certificate was presented during authentication, this method returns the value of the requested option in the corresponding authorized_keys entry if it was set. Otherwise, it returns the default value provided.

    The following standard options are supported:

    > command (string)
    > environment (dictionary of name/value pairs)
    > from (list of host patterns)
    > permitopen (list of host/port tuples)
    > principals (list of usernames)

    Non-standard options are also supported and will return the value `True` if the option is present without a value or return a list of strings containing the values associated with each occurrence of that option name. If the option is not present, the specified default value is returned.

    Parameters:

    - option (string) – The name of the option to look up.
    - default – The default value to return if the option is not present.

    Returns: | The value of the option in authorized_keys, if set

  `check_key_permission`(permission)

    Check permissions in authorized_keys

    If a client key or certificate was presented during authentication, this method returns whether the specified permission is allowed by the corresponding authorized_keys entry. By default, all permissions are granted, but they can be revoked by specifying an option starting with ‘no-‘ without a value.

    The following standard options are supported:

    > X11-forwarding
    > agent-forwarding
    > port-forwarding
    > pty
    > user-rc

    AsyncSSH internally enforces port-forwarding and pty permissions but ignores the other values since it does not implement those features.

    Non-standard permissions can also be checked, as long as the option follows the convention of starting with ‘no-‘.

    Parameters: | permission (string) – The name of the permission to check (without the ‘no-‘).
    Returns: | A boolean indicating if the permission is granted.

  `get_certificate_option`(option, default=None)

    Return option from user certificate

    If a user certificate was presented during authentication, this method returns the value of the requested option in the certificate if it was set. Otherwise, it returns the default value provided.

    The following options are supported:

    > force-command (string)
    > source-address (list of CIDR-style IP network addresses)

    Parameters:

    - option (string) – The name of the option to look up.
    - default – The default value to return if the option is not present.

    Returns: | The value of the option in the user certificate, if set

  `check_certificate_permission`(permission)

    Check permissions in user certificate

    If a user certificate was presented during authentication, this method returns whether the specified permission was granted in the certificate. Otherwise, it acts as if all permissions are granted and returns `True`.

    The following permissions are supported:

    > X11-forwarding
    > agent-forwarding
    > port-forwarding
    > pty
    > user-rc

    AsyncSSH internally enforces port-forwarding and pty permissions but ignores the other values since it does not implement those features.

    Parameters: | permission (string) – The name of the permission to check (without the ‘permit-‘).
    Returns: | A boolean indicating if the permission is granted.

  Server connection open methods |
  --- | ---

  `create_connection`(session_factory, listen_host, listen_port, orig_host='', orig_port=0, *, encoding=None, window=2097152, max_pktsize=32768)

    Create an SSH TCP forwarded connection

    This method is a coroutine which can be called to notify the client about a new inbound TCP connection arriving on the specified listening host and port. If the connection is successfully opened, a new SSH channel will be opened with data being handled by a `SSHTCPSession` object created by `session_factory`.

    Optional arguments include the host and port of the original client opening the connection when performing TCP port forwarding.

    By default, this class expects data to be sent and received as raw bytes. However, an optional encoding argument can be passed in to select the encoding to use, allowing the application send and receive string data.

    Other optional arguments include the SSH receive window size and max packet size which default to 2 MB and 32 KB, respectively.

    Parameters:

    - session_factory (callable) – A callable which returns an `SSHClientSession` object that will be created to handle activity on this session
    - listen_host (string) – The hostname or address of the listener receiving the connection
    - listen_port (integer) – The port number of the listener receiving the connection
    - orig_host (string) – (optional) The hostname or address of the client requesting the connection
    - orig_port (integer) – (optional) The port number of the client requesting the connection
    - encoding (string) – (optional) The Unicode encoding to use for data exchanged on the connection
    - window (integer) – (optional) The receive window size for this session
    - max_pktsize (integer) – (optional) The maximum packet size for this session

    Returns: | an `SSHTCPChannel` and `SSHTCPSession`

  `open_connection`(handler_factory, *args, **kwargs)

    Open an SSH TCP forwarded connection

    This method is a coroutine wrapper around `create_connection()` designed to provide a “high-level” stream interface for creating an SSH TCP forwarded connection. Instead of taking a `session_factory` argument for constructing an object which will handle activity on the session via callbacks, it returns `SSHReader` and `SSHWriter` objects which can be used to perform I/O on the connection.

    With the exception of `session_factory`, all of the arguments to `create_connection()` are supported and have the same meaning here.

    Returns: | an `SSHReader` and `SSHWriter`

  Server forwarding methods |
  --- | ---

  `forward_connection`(dest_host, dest_port)

    Forward a tunneled SSH connection

    This method is a coroutine which can be returned by a `session_factory` to forward connections tunneled over SSH to the specified destination host and port.

    Parameters:

    - dest_host (string) – The hostname or address to forward the connections to
    - dest_port (integer) – The port number to forward the connections to

    Returns: | coroutine that returns an `SSHTCPSession`

  Server channel creation methods |
  --- | ---

  `create_server_channel`(encoding='utf-8', window=2097152, max_pktsize=32768)

    Create an SSH server channel for a new SSH session

    This method can be called by `session_requested()` to create an `SSHServerChannel` with the desired encoding, window, and max packet size for a newly created SSH server session.

    Parameters:

    - encoding (string) – (optional) The Unicode encoding to use for data exchanged on the session, defaulting to UTF-8 (ISO 10646) format. If `None` is passed in, the application can send and receive raw bytes.
    - window (integer) – (optional) The receive window size for this session
    - max_pktsize (integer) – (optional) The maximum packet size for this session

    Returns: | `SSHServerChannel`

  `create_tcp_channel`(encoding=None, window=2097152, max_pktsize=32768)

    Create an SSH TCP channel for a new direct TCP connection

    This method can be called by `connection_requested()` to create an `SSHTCPChannel` with the desired encoding, window, and max packet size for a newly created SSH direct connection.

    Parameters:

    - encoding (string) – (optional) The Unicode encoding to use for data exchanged on the connection. This defaults to `None`, allowing the application to send and receive raw bytes.
    - window (integer) – (optional) The receive window size for this session
    - max_pktsize (integer) – (optional) The maximum packet size for this session

    Returns: | `SSHTCPChannel`

  Connection close methods |
  --- | ---

  `abort`()

    Forcibly close the SSH connection

    This method closes the SSH connection immediately, without waiting for pending operations to complete and wihtout sending an explicit SSH disconnect message. Buffered data waiting to be sent will be lost and no more data will be received. When the the connection is closed, `connection_lost()` on the associated `SSHClient` object will be called with the value `None`.

  `close`()

    Cleanly close the SSH connection

    This method calls `disconnect()` with the reason set to indicate that the connection was closed explicitly by the application.

  `disconnect`(code, reason, lang='en-US')

    Disconnect the SSH connection

    This method sends a disconnect message and closes the SSH connection after buffered data waiting to be written has been sent. No more data will be received. When the connection is fully closed, `connection_lost()` on the associated `SSHClient` or `SSHServer` object will be called with the value `None`.

    Parameters:

    - code (integer) – The reason for the disconnect, from disconnect reason codes
    - reason (string) – A human readable reason for the disconnect
    - lang (string) – The language the reason is in

## Session Classes

### SSHClientSession

class `asyncssh.``SSHClientSession`

  SSH client session handler

  Applications should subclass this when implementing an SSH client session handler. The functions listed below should be implemented to define application-specific behavior. In particular, the standard `asyncio` protocol methods such as `connection_made()`, `connection_lost()`, `data_received()`, `eof_received()`, `pause_writing()`, and `resume_writing()` are all supported. In addition, `session_started()` is called as soon as the SSH session is fully started, `xon_xoff_requested()` can be used to determine if the server wants the client to support XON/XOFF flow control, and `exit_status_received()` and `exit_signal_received()` can be used to receive session exit information.

  General session handlers |
  --- | ---

  `connection_made`(chan)

    Called when a channel is opened successfully

    This method is called when a channel is opened successfully. The channel parameter should be stored if needed for later use.

    Parameters: | chan (`SSHClientChannel`) – The channel which was successfully opened.

  `connection_lost`(exc)

    Called when a channel is closed

    This method is called when a channel is closed. If the channel is shut down cleanly, exc will be `None`. Otherwise, it will be an exception explaining the reason for the channel close.

    Parameters: | exc (`Exception`) – The exception which caused the channel to close, or `None` if the channel closed cleanly.

  `session_started`()

    Called when the session is started

    This method is called when a session has started up. For client and server sessions, this will be called once a shell, exec, or subsystem request has been successfully completed. For TCP sessions, it will be called immediately after the connection is opened.

  General session read handlers |
  --- | ---

  `data_received`(data, datatype)

    Called when data is received on the channel

    This method is called when data is received on the channel. If an encoding was specified when the channel was created, the data will be delivered as a string after decoding with the requested encoding. Otherwise, the data will be delivered as bytes.

    Parameters:

    - data (string or bytes) – The data received on the channel
    - datatype – The extended data type of the data, from extended data types

  `eof_received`()

    Called when EOF is received on the channel

    This method is called when an end-of-file indication is received on the channel, after which no more data will be received. If this method returns `True`, the channel remains half open and data may still be sent. Otherwise, the channel is automatically closed after this method returns. This is the default behavior.

  General session write handlers |
  --- | ---

  `pause_writing`()

    Called when the write buffer becomes full

    This method is called when the channel’s write buffer becomes full and no more data can be sent until the remote system adjusts its window. While data can still be buffered locally, applications may wish to stop producing new data until the write buffer has drained.

  `resume_writing`()

    Called when the write buffer has sufficiently drained

    This method is called when the channel’s send window reopens and enough data has drained from the write buffer to allow the application to produce more data.

  Other client session handlers |
  --- | ---

  `xon_xoff_requested`(client_can_do)

    XON/XOFF flow control has been enabled or disabled

    This method is called to notify the client whether or not to enable XON/XOFF flow control. If client_can_do is `True` and output is being sent to an interactive terminal the application should allow input of Control-S and Control-Q to pause and resume output, respectively. If client_can_do is `False`, Control-S and Control-Q should be treated as normal input and passed through to the server. Non-interactive applications can ignore this request.

    By default, this message is ignored.

    Parameters: | client_can_do (boolean) – Whether or not to enable XON/XOFF flow control

  `exit_status_received`(status)

    A remote exit status has been received for this session

    This method is called when the shell, command, or subsystem running on the server terminates and returns an exit status. A zero exit status generally means that the operation was successful. This call will generally be followed by a call to `connection_lost()`.

    By default, the exit status is ignored.

    Parameters: | status (integer) – The exit status returned by the remote process

  `exit_signal_received`(signal, core_dumped, msg, lang)

    A remote exit signal has been received for this session

    This method is called when the shell, command, or subsystem running on the server terminates abnormally with a signal. A more detailed error may also be provided, along with an indication of whether the remote process dumped core. This call will generally be followed by a call to `connection_lost()`.

    By default, exit signals are ignored.

    Parameters:

    - signal (string) – The signal which caused the remote process to exit
    - core_dumped (boolean) – Whether or not the remote process dumped core
    - msg – Details about what error occurred
    - lang – The language the error message is in

### SSHServerSession

class `asyncssh.``SSHServerSession`

  SSH server session handler

  Applications should subclass this when implementing an SSH server session handler. The functions listed below should be implemented to define application-specific behavior. In particular, the standard `asyncio` protocol methods such as `connection_made()`, `connection_lost()`, `data_received()`, `eof_received()`, `pause_writing()`, and `resume_writing()` are all supported. In addition, `pty_requested()` is called when the client requests a pseudo-terminal, one of `shell_requested()`, `exec_requested()`, or `subsystem_requested()` is called depending on what type of session the client wants to start, `session_started()` is called once the SSH session is fully started, `terminal_size_changed()` is called when the client’s terminal size changes, `signal_received()` is called when the client sends a signal, and `break_received()` is called when the client sends a break.

  General session handlers |
  --- | ---

  `connection_made`(chan)

    Called when a channel is opened successfully

    This method is called when a channel is opened successfully. The channel parameter should be stored if needed for later use.

    Parameters: | chan (`SSHClientChannel`) – The channel which was successfully opened.

  `connection_lost`(exc)

    Called when a channel is closed

    This method is called when a channel is closed. If the channel is shut down cleanly, exc will be `None`. Otherwise, it will be an exception explaining the reason for the channel close.

    Parameters: | exc (`Exception`) – The exception which caused the channel to close, or `None` if the channel closed cleanly.

  `session_started`()

    Called when the session is started

    This method is called when a session has started up. For client and server sessions, this will be called once a shell, exec, or subsystem request has been successfully completed. For TCP sessions, it will be called immediately after the connection is opened.

  Server session open handlers |
  --- | ---

  `pty_requested`(term_type, term_size, term_modes)

    A psuedo-terminal has been requested

    This method is called when the client sends a request to allocate a pseudo-terminal with the requested terminal type, size, and POSIX terminal modes. This method should return `True` if the request for the pseudo-terminal is accepted. Otherwise, it should return `False` to reject the request.

    By default, requests to allocate a pseudo-terminal are accepted but nothing is done with the associated terminal information. Applications wishing to use this information should implement this method and have it return `True`, or call `get_terminal_type()`, `get_terminal_size()`, or `get_terminal_mode()` on the `SSHServerChannel` to get the information they need after a shell, command, or subsystem is started.

    Parameters:

    - term (string) – Terminal type to set for this session
    - term_size (tuple) – Terminal size to set for this session provided as a tuple of four integers: the width and height of the terminal in characters followed by the width and height of the terminal in pixels
    - term_modes (dictionary) – POSIX terminal modes to set for this session, where keys are taken from POSIX terminal modes with values defined in section 8 of RFC 4254#section-8.

    Returns: | A boolean indicating if the request for a pseudo-terminal was allowed or not

  `shell_requested`()

    The client has requested a shell

    This method should be implemented by the application to perform whatever processing is required when a client makes a request to open an interactive shell. It should return `True` to accept the request, or `False` to reject it.

    If the application returns `True`, the `session_started()` method will be called once the channel is fully open. No output should be sent until this method is called.

    By default this method returns `False` to reject all requests.

    Returns: | A boolean indicating if the shell request was allowed or not

  `exec_requested`(command)

    The client has requested to execute a command

    This method should be implemented by the application to perform whatever processing is required when a client makes a request to execute a command. It should return `True` to accept the request, or `False` to reject it.

    If the application returns `True`, the `session_started()` method will be called once the channel is fully open. No output should be sent until this method is called.

    By default this method returns `False` to reject all requests.

    Parameters: | command (string) – The command the client has requested to execute
    Returns: | A boolean indicating if the exec request was allowed or not

  `subsystem_requested`(subsystem)

    The client has requested to start a subsystem

    This method should be implemented by the application to perform whatever processing is required when a client makes a request to start a subsystem. It should return `True` to accept the request, or `False` to reject it.

    If the application returns `True`, the `session_started()` method will be called once the channel is fully open. No output should be sent until this method is called.

    By default this method returns `False` to reject all requests.

    Parameters: | subsystem (string) – The subsystem to start
    Returns: | A boolean indicating if the request to open the subsystem was allowed or not

  General session read handlers |
  --- | ---

  `data_received`(data, datatype)

    Called when data is received on the channel

    This method is called when data is received on the channel. If an encoding was specified when the channel was created, the data will be delivered as a string after decoding with the requested encoding. Otherwise, the data will be delivered as bytes.

    Parameters:

    - data (string or bytes) – The data received on the channel
    - datatype – The extended data type of the data, from extended data types

  `eof_received`()

    Called when EOF is received on the channel

    This method is called when an end-of-file indication is received on the channel, after which no more data will be received. If this method returns `True`, the channel remains half open and data may still be sent. Otherwise, the channel is automatically closed after this method returns. This is the default behavior.

  General session write handlers |
  --- | ---

  `pause_writing`()

    Called when the write buffer becomes full

    This method is called when the channel’s write buffer becomes full and no more data can be sent until the remote system adjusts its window. While data can still be buffered locally, applications may wish to stop producing new data until the write buffer has drained.

  `resume_writing`()

    Called when the write buffer has sufficiently drained

    This method is called when the channel’s send window reopens and enough data has drained from the write buffer to allow the application to produce more data.

  Other server session handlers |
  --- | ---

  `break_received`(msec)

    The client has sent a break

    This method is called when the client requests that the server perform a break operation on the terminal. If the break is performed, this method should return `True`. Otherwise, it should return `False`.

    By default, this method returns `False` indicating that no break was performed.

    Parameters: | msec (integer) – The duration of the break in milliseconds
    Returns: | A boolean to indicate if the break operation was performed or not

  `signal_received`(signal)

    The client has sent a signal

    This method is called when the client delivers a signal on the channel.

    By default, signals from the client are ignored.

  `terminal_size_changed`(width, height, pixwidth, pixheight)

    The terminal size has changed

    This method is called when a client requests a pseudo-terminal and again whenever the the size of he client’s terminal window changes.

    By default, this information is ignored, but applications wishing to use the terminal size can implement this method to get notified whenever it changes.

    Parameters:

    - width (integer) – The width of the terminal in characters
    - height (integer) – The height of the terminal in characters
    - pixwidth (integer) – (optional) The width of the terminal in pixels
    - pixheight (integer) – (optional) The height of the terminal in pixels

### SSHTCPSession

class `asyncssh.``SSHTCPSession`

  SSH TCP connection session handler

  Applications should subclass this when implementing a handler for SSH direct or forwarded TCP connections.

  SSH client applications wishing to open a direct connection should call `create_connection()` on their `SSHClientConnection`, passing in a factory which returns instances of this class.

  Server applications wishing to allow direct connections should implement the coroutine `connection_requested()` on their `SSHServer` object and have it return instances of this class.

  Server applications wishing to allow connection forwarding back to the client should implement the coroutine `server_requested()` on their `SSHServer` object and call `create_connection()` on their `SSHServerConnection` for each new connection, passing it a factory which returns instances of this class.

  When a connection is successfully opened, `session_started()` will be called, after which the application can begin sending data. Received data will be passed to the `data_received()` method.

  General session handlers |
  --- | ---

  `connection_made`(chan)

    Called when a channel is opened successfully

    This method is called when a channel is opened successfully. The channel parameter should be stored if needed for later use.

    Parameters: | chan (`SSHClientChannel`) – The channel which was successfully opened.

  `connection_lost`(exc)

    Called when a channel is closed

    This method is called when a channel is closed. If the channel is shut down cleanly, exc will be `None`. Otherwise, it will be an exception explaining the reason for the channel close.

    Parameters: | exc (`Exception`) – The exception which caused the channel to close, or `None` if the channel closed cleanly.

  `session_started`()

    Called when the session is started

    This method is called when a session has started up. For client and server sessions, this will be called once a shell, exec, or subsystem request has been successfully completed. For TCP sessions, it will be called immediately after the connection is opened.

  General session read handlers |
  --- | ---

  `data_received`(data, datatype)

    Called when data is received on the channel

    This method is called when data is received on the channel. If an encoding was specified when the channel was created, the data will be delivered as a string after decoding with the requested encoding. Otherwise, the data will be delivered as bytes.

    Parameters:

    - data (string or bytes) – The data received on the channel
    - datatype – The extended data type of the data, from extended data types

  `eof_received`()

    Called when EOF is received on the channel

    This method is called when an end-of-file indication is received on the channel, after which no more data will be received. If this method returns `True`, the channel remains half open and data may still be sent. Otherwise, the channel is automatically closed after this method returns. This is the default behavior.

  General session write handlers |
  --- | ---

  `pause_writing`()

    Called when the write buffer becomes full

    This method is called when the channel’s write buffer becomes full and no more data can be sent until the remote system adjusts its window. While data can still be buffered locally, applications may wish to stop producing new data until the write buffer has drained.

  `resume_writing`()

    Called when the write buffer has sufficiently drained

    This method is called when the channel’s send window reopens and enough data has drained from the write buffer to allow the application to produce more data.

## Channel Classes

### SSHClientChannel

class `asyncssh.``SSHClientChannel`

  SSH client channel

  General channel methods |
  --- | ---

  `get_extra_info`(name, default=None)

    Get additional information about the channel

    This method returns extra information about the channel once it is established. Supported values include `'connection'` to return the SSH connection this channel is running over plus all of the values supported on that connection.

    For TCP channels, the values `'local_peername'` and `'remote_peername'` are added to return the local and remote host and port information for the tunneled TCP connection.

    See `get_extra_info()` on `SSHClientConnection` for more information.

  Client channel read methods |
  --- | ---

  `pause_reading`()

    Pause delivery of incoming data

    This method is used to temporarily suspend delivery of incoming channel data. After this call, incoming data will no longer be delivered until `resume_reading()` is called. Data will be buffered locally up to the configured SSH channel window size, but window updates will no longer be sent, eventually causing back pressure on the remote system.

    Note

    Channel close notifications are not suspended by this call. If the remote system closes the channel while delivery is suspended, the channel will be closed even though some buffered data may not have been delivered.

  `resume_reading`()

    Resume delivery of incoming data

    This method can be called to resume delivery of incoming data which was suspended by a call to `pause_reading()`. As soon as this method is called, any buffered data will be delivered immediately. A pending end-of-file notication may also be delivered if one was queued while reading was paused.

  Client channel write methods |
  --- | ---

  `can_write_eof`()

    Return whether the channel supports `write_eof()`

    This method always returns `True`.

  `get_write_buffer_size`()

    Return the current size of the channel’s output buffer

    This method returns how many bytes are currently in the channel’s output buffer waiting to be written.

  `set_write_buffer_limits`(high=None, low=None)

    Set the high- and low-water limits for write flow control

    This method sets the limits used when deciding when to call the `pause_writing()` and `resume_writing()` methods on SSH sessions. Writing will be paused when the write buffer size exceeds the high-water mark, and resumed when the write buffer size equals or drops below the low-water mark.

  `write`(data, datatype=None)

    Write data on the channel

    This method can be called to send data on the channel. If an encoding was specified when the channel was created, the data should be provided as a string and will be converted using that encoding. Otherwise, the data should be provided as bytes.

    An extended data type can optionally be provided. For instance, this is used from a `SSHServerSession` to write data to `stderr`.

    Parameters:

    - data (string or bytes) – The data to send on the channel
    - datatype (integer) – (optional) The extended data type of the data, from extended data types

    Raises: | `OSError` if the channel isn’t open for sending or the extended data type is not valid for this type of channel

  `writelines`(list_of_data, datatype=None)

    Write a list of data bytes on the channel

    This method can be called to write a list (or any iterable) of data bytes to the channel. It is functionality equivalent to calling `write()` on each element in the list.

    Parameters:

    - list_of_data (iterable of `string` or `bytes` objects) – The data to send on the channel
    - datatype (integer) – (optional) The extended data type of the data, from extended data types

    Raises: | `OSError` if the channel isn’t open for sending or the extended data type is not valid for this type of channel

  `write_eof`()

    Write EOF on the channel

    This method sends an end-of-file indication on the channel, after which no more data can be sent. The channel remains open, though, and data may still be sent in the other direction.

    Raises: | `OSError` if the channel isn’t open for sending

  Other client channel methods |
  --- | ---

  `get_exit_status`()

    Return the session’s exit status

    This method returns the exit status of the session if one has been sent. If an exit signal was received, this method returns -1 and the exit signal information can be collected by calling `get_exit_signal()`. If neither has been sent, this method returns `None`.

  `get_exit_signal`()

    Return the session’s exit signal, if one was sent

    This method returns information about the exit signal sent on this session. If an exit signal was sent, a tuple is returned containing the signal name, a boolean for whether a core dump occurred, a message associated with the signal, and the language the message was in. If no exit signal was sent, `None` is returned.

  `change_terminal_size`(width, height, pixwidth=0, pixheight=0)

    Change the terminal window size for this session

    This method changes the width and height of the terminal associated with this session.

    Parameters:

    - width (integer) – The width of the terminal in characters
    - height (integer) – The height of the terminal in characters
    - pixwidth (integer) – (optional) The width of the terminal in pixels
    - pixheight (integer) – (optional) The height of the terminal in pixels

  `send_break`(msec)

    Send a break to the remote process

    This method requests that the server perform a break operation on the remote process or service as described in RFC 4335.

    Parameters: | msec (integer) – The duration of the break in milliseconds
    Raises: | `OSError` if the channel is not open

  `send_signal`(signal)

    Send a signal to the remote process

    This method can be called to deliver a signal to the remote process or service. Signal names should be as described in section 6.10 of RFC 4254#section-6.10.

    Parameters: | signal (string) – The signal to deliver
    Raises: | `OSError` if the channel is not open

  `kill`()

    Forcibly kill the remote process

    This method can be called to forcibly stop the remote process or service by sending it a `KILL` signal.

    Raises: | `OSError` if the channel is not open

  `terminate`()

    Terminate the remote process

    This method can be called to terminate the remote process or service by sending it a `TERM` signal.

    Raises: | `OSError` if the channel is not open

  General channel close methods |
  --- | ---

  `abort`()

    Forcibly close the channel

    This method can be called to forcibly close the channel, after which no more data can be sent or received. Any unsent buffered data and any incoming data in flight will be discarded.

  `close`()

    Cleanly close the channel

    This method can be called to cleanly close the channel, after which no more data can be sent or received. Any unsent buffered data will be flushed asynchronously before the channel is closed.

  `wait_closed`()

    Wait for this channel to close

    This method is a coroutine which can be called to block until this channel has finished closing.

### SSHServerChannel

class `asyncssh.``SSHServerChannel`

  SSH server channel

  General channel methods |
  --- | ---

  `get_extra_info`(name, default=None)

    Get additional information about the channel

    This method returns extra information about the channel once it is established. Supported values include `'connection'` to return the SSH connection this channel is running over plus all of the values supported on that connection.

    For TCP channels, the values `'local_peername'` and `'remote_peername'` are added to return the local and remote host and port information for the tunneled TCP connection.

    See `get_extra_info()` on `SSHClientConnection` for more information.

  Server channel info methods |
  --- | ---

  `get_environment`()

    Return the environment for this session

    This method returns the environment set by the client when the session was opened. Calls to this method should only be made after `session_started` has been called on the `SSHServerSession`.

    Returns: | A dictionary containing the environment variables set by the client

  `get_command`()

    Return the command the client requested to execute, if any

    This method returns the command the client requested to execute when the session was opened, if any. If the client did not request that a command be executed, this method will return `None`. Calls to this method should only be made after `session_started` has been called on the `SSHServerSession`. When using the stream-based API, calls to this can be made at any time after the handler function has started up.

  `get_subsystem`()

    Return the subsystem the client requested to open, if any

    This method returns the subsystem the client requested to open when the session was opened, if any. If the client did not request that a subsystem be opened, this method will return `None`. Calls to this method should only be made after `session_started` has been called on the `SSHServerSession`. When using the stream-based API, calls to this can be made at any time after the handler function has started up.

  `get_terminal_type`()

    Return the terminal type for this session

    This method returns the terminal type set by the client when the session was opened. If the client didn’t request a pseudo-terminal, this method will return `None`. Calls to this method should only be made after `session_started` has been called on the `SSHServerSession`. When using the stream-based API, calls to this can be made at any time after the handler function has started up.

    Returns: | A string containing the terminal type or `None` if no pseudo-terminal was requested

  `get_terminal_size`()

    Return terminal size information for this session

    This method returns the latest terminal size information set by the client. If the client didn’t set any terminal size information, all values returned will be zero. Calls to this method should only be made after `session_started` has been called on the `SSHServerSession`. When using the stream-based API, calls to this can be made at any time after the handler function has started up.

    Also see `terminal_size_changed()` or the `TerminalSizeChanged` exception for how to get notified when the terminal size changes.

    Returns: | A tuple of four integers containing the width and height of the terminal in characters and the width and height of the terminal in pixels

  `get_terminal_mode`(mode)

    Return the requested TTY mode for this session

    This method looks up the value of a POSIX terminal mode set by the client when the session was opened. If the client didn’t request a pseudo-terminal or didn’t set the requested TTY mode opcode, this method will return `None`. Calls to this method should only be made after `session_started` has been called on the `SSHServerSession`. When using the stream-based API, calls to this can be made at any time after the handler function has started up.

    Parameters: | mode (integer) – POSIX terminal mode taken from POSIX terminal modes to look up
    Returns: | An integer containing the value of the requested POSIX terminal mode or `None` if the requested mode was not set

  Server channel read methods |
  --- | ---

  `pause_reading`()

    Pause delivery of incoming data

    This method is used to temporarily suspend delivery of incoming channel data. After this call, incoming data will no longer be delivered until `resume_reading()` is called. Data will be buffered locally up to the configured SSH channel window size, but window updates will no longer be sent, eventually causing back pressure on the remote system.

    Note

    Channel close notifications are not suspended by this call. If the remote system closes the channel while delivery is suspended, the channel will be closed even though some buffered data may not have been delivered.

  `resume_reading`()

    Resume delivery of incoming data

    This method can be called to resume delivery of incoming data which was suspended by a call to `pause_reading()`. As soon as this method is called, any buffered data will be delivered immediately. A pending end-of-file notication may also be delivered if one was queued while reading was paused.

  Server channel write methods |
  --- | ---

  `can_write_eof`()

    Return whether the channel supports `write_eof()`

    This method always returns `True`.

  `get_write_buffer_size`()

    Return the current size of the channel’s output buffer

    This method returns how many bytes are currently in the channel’s output buffer waiting to be written.

  `set_write_buffer_limits`(high=None, low=None)

    Set the high- and low-water limits for write flow control

    This method sets the limits used when deciding when to call the `pause_writing()` and `resume_writing()` methods on SSH sessions. Writing will be paused when the write buffer size exceeds the high-water mark, and resumed when the write buffer size equals or drops below the low-water mark.

  `write`(data, datatype=None)

    Write data on the channel

    This method can be called to send data on the channel. If an encoding was specified when the channel was created, the data should be provided as a string and will be converted using that encoding. Otherwise, the data should be provided as bytes.

    An extended data type can optionally be provided. For instance, this is used from a `SSHServerSession` to write data to `stderr`.

    Parameters:

    - data (string or bytes) – The data to send on the channel
    - datatype (integer) – (optional) The extended data type of the data, from extended data types

    Raises: | `OSError` if the channel isn’t open for sending or the extended data type is not valid for this type of channel

  `writelines`(list_of_data, datatype=None)

    Write a list of data bytes on the channel

    This method can be called to write a list (or any iterable) of data bytes to the channel. It is functionality equivalent to calling `write()` on each element in the list.

    Parameters:

    - list_of_data (iterable of `string` or `bytes` objects) – The data to send on the channel
    - datatype (integer) – (optional) The extended data type of the data, from extended data types

    Raises: | `OSError` if the channel isn’t open for sending or the extended data type is not valid for this type of channel

  `write_stderr`(data)

    Write output to stderr

    This method can be called to send output to the client which is intended to be displayed on stderr. If an encoding was specified when the channel was created, the data should be provided as a string and will be converted using that encoding. Otherwise, the data should be provided as bytes.

    Parameters: | data (string or bytes) – The data to send to stderr
    Raises: | `OSError` if the channel isn’t open for sending

  `writelines_stderr`(list_of_data)

    Write a list of data bytes to stderr

    This method can be called to write a list (or any iterable) of data bytes to the channel. It is functionality equivalent to calling `write_stderr()` on each element in the list.

  `write_eof`()

    Write EOF on the channel

    This method sends an end-of-file indication on the channel, after which no more data can be sent. The channel remains open, though, and data may still be sent in the other direction.

    Raises: | `OSError` if the channel isn’t open for sending

  Other server channel methods |
  --- | ---

  `start_sftp_server`(sftp_factory)

    Start an SFTP server for this session

    This method can be used by an existing `SSHServerSession` to replace itself with an SFTP server session. Calls to this method should be made from `session_started` before any data is read or written. Once called, no further calls will be made on the original session.

    > Note

    > The `connection_lost` method will not be called on the original server session when this is used.

    Parameters: | sftp_server (callable) – A callable which returns an `SFTPServer` object that will be created to handle SFTP requests on this channel.

  `set_xon_xoff`(client_can_do)

    Set whether the client should enable XON/XOFF flow control

    This method can be called to tell the client whether or not to enable XON/XOFF flow control, indicating that it should intercept Control-S and Control-Q coming from its local terminal to pause and resume output, respectively. Applications should set client_can_do to `True` to enable this functionality or to `False` to tell the client to forward Control-S and Control-Q through as normal input.

    Parameters: | client_can_do (boolean) – Whether or not the client should enable XON/XOFF flow control

  `exit`(status)

    Send exit status and close the channel

    This method can be called to report an exit status for the process back to the client and close the channel. A zero exit status is generally returned when the operation was successful. After reporting the status, the channel is closed.

    Parameters: | status (integer) – The exit status to report to the client
    Raises: | `OSError` if the channel isn’t open

  `exit_with_signal`(signal, core_dumped=False, msg='', lang='en-US')

    Send exit signal and close the channel

    This method can be called to report that the process terminated abnormslly with a signal. A more detailed error message may also provided, along with an indication of whether or not the process dumped core. After reporting the signal, the channel is closed.

    Parameters:

    - signal (string) – The signal which caused the process to exit
    - core_dumped (boolean) – (optional) Whether or not the process dumped core
    - msg – (optional) Details about what error occurred
    - lang – (optional) The language the error message is in

    Raises: | `OSError` if the channel isn’t open

  General channel close methods |
  --- | ---

  `abort`()

    Forcibly close the channel

    This method can be called to forcibly close the channel, after which no more data can be sent or received. Any unsent buffered data and any incoming data in flight will be discarded.

  `close`()

    Cleanly close the channel

    This method can be called to cleanly close the channel, after which no more data can be sent or received. Any unsent buffered data will be flushed asynchronously before the channel is closed.

  `wait_closed`()

    Wait for this channel to close

    This method is a coroutine which can be called to block until this channel has finished closing.

### SSHTCPChannel

class `asyncssh.``SSHTCPChannel`

  SSH TCP channel

  General channel methods |
  --- | ---

  `get_extra_info`(name, default=None)

    Get additional information about the channel

    This method returns extra information about the channel once it is established. Supported values include `'connection'` to return the SSH connection this channel is running over plus all of the values supported on that connection.

    For TCP channels, the values `'local_peername'` and `'remote_peername'` are added to return the local and remote host and port information for the tunneled TCP connection.

    See `get_extra_info()` on `SSHClientConnection` for more information.

  General channel read methods |
  --- | ---

  `pause_reading`()

    Pause delivery of incoming data

    This method is used to temporarily suspend delivery of incoming channel data. After this call, incoming data will no longer be delivered until `resume_reading()` is called. Data will be buffered locally up to the configured SSH channel window size, but window updates will no longer be sent, eventually causing back pressure on the remote system.

    Note

    Channel close notifications are not suspended by this call. If the remote system closes the channel while delivery is suspended, the channel will be closed even though some buffered data may not have been delivered.

  `resume_reading`()

    Resume delivery of incoming data

    This method can be called to resume delivery of incoming data which was suspended by a call to `pause_reading()`. As soon as this method is called, any buffered data will be delivered immediately. A pending end-of-file notication may also be delivered if one was queued while reading was paused.

  General channel write methods |
  --- | ---

  `can_write_eof`()

    Return whether the channel supports `write_eof()`

    This method always returns `True`.

  `get_write_buffer_size`()

    Return the current size of the channel’s output buffer

    This method returns how many bytes are currently in the channel’s output buffer waiting to be written.

  `set_write_buffer_limits`(high=None, low=None)

    Set the high- and low-water limits for write flow control

    This method sets the limits used when deciding when to call the `pause_writing()` and `resume_writing()` methods on SSH sessions. Writing will be paused when the write buffer size exceeds the high-water mark, and resumed when the write buffer size equals or drops below the low-water mark.

  `write`(data, datatype=None)

    Write data on the channel

    This method can be called to send data on the channel. If an encoding was specified when the channel was created, the data should be provided as a string and will be converted using that encoding. Otherwise, the data should be provided as bytes.

    An extended data type can optionally be provided. For instance, this is used from a `SSHServerSession` to write data to `stderr`.

    Parameters:

    - data (string or bytes) – The data to send on the channel
    - datatype (integer) – (optional) The extended data type of the data, from extended data types

    Raises: | `OSError` if the channel isn’t open for sending or the extended data type is not valid for this type of channel

  `writelines`(list_of_data, datatype=None)

    Write a list of data bytes on the channel

    This method can be called to write a list (or any iterable) of data bytes to the channel. It is functionality equivalent to calling `write()` on each element in the list.

    Parameters:

    - list_of_data (iterable of `string` or `bytes` objects) – The data to send on the channel
    - datatype (integer) – (optional) The extended data type of the data, from extended data types

    Raises: | `OSError` if the channel isn’t open for sending or the extended data type is not valid for this type of channel

  `write_eof`()

    Write EOF on the channel

    This method sends an end-of-file indication on the channel, after which no more data can be sent. The channel remains open, though, and data may still be sent in the other direction.

    Raises: | `OSError` if the channel isn’t open for sending

  General channel close methods |
  --- | ---

  `abort`()

    Forcibly close the channel

    This method can be called to forcibly close the channel, after which no more data can be sent or received. Any unsent buffered data and any incoming data in flight will be discarded.

  `close`()

    Cleanly close the channel

    This method can be called to cleanly close the channel, after which no more data can be sent or received. Any unsent buffered data will be flushed asynchronously before the channel is closed.

  `wait_closed`()

    Wait for this channel to close

    This method is a coroutine which can be called to block until this channel has finished closing.

## Listener Classes

### SSHListener

class `asyncssh.``SSHListener`

  SSH listener for inbound TCP connections

  `get_port`()

    Return the port number being listened on

    This method returns the port number that the remote listener was bound to. When the requested remote listening port is `0` to indicate a dynamic port, this method can be called to determine what listening port was selected.

    Returns: | The port number being listened on

  `close`()

    Stop listening for new connections

    This method can be called to stop listening for connections. Existing connections will remain open.

  `wait_closed`()

    Wait for the listener to close

    This method is a coroutine which waits for the associated TCP listeners to be closed.

## Stream Classes

### SSHReader

class `asyncssh.``SSHReader`(session, chan, datatype=None)

  SSH read stream handler

  `channel`

    The SSH channel associated with this stream

  `get_extra_info`(name, default=None)

    Return additional information about this stream

    This method returns extra information about the channel associated with this stream. See `get_extra_info()` on `SSHClientChannel` for additional information.

  `at_eof`()

    Return whether the stream is at EOF

    This method returns `True` when EOF has been received and all data in the stream has been read.

  `read`(n=-1)

    Read data from the stream

    This method is a coroutine which reads up to `n` bytes or characters from the stream. If `n` is not provided or set to `-1`, it reads until EOF or until a signal is received on the stream.

    If EOF was received and the receive buffer is empty, an empty `bytes` or `string` object is returned.

    Note

    Unlike traditional `asyncio` stream readers, the data will be delivered as either bytes or a string depending on whether an encoding was specified when the underlying channel was opened.

  `readline`()

    Read one line from the stream

    This method is a coroutine which reads one line, ending in `'\n'`.

    If EOF was received before `'\n'` was found, the partial line is returned. If EOF was received and the receive buffer is empty, an empty `bytes` or `string` object is returned.

  `readexactly`(n)

    Read an exact amount of data from the stream

    This method is a coroutine which reads exactly n bytes or characters from the stream.

    If EOF is received before `n` bytes are read, an `IncompleteReadError` is raised and its `partial` attribute contains the partially read data.

### SSHWriter

class `asyncssh.``SSHWriter`(session, chan, datatype=None)

  SSH write stream handler

  `channel`

    The SSH channel associated with this stream

  `get_extra_info`(name, default=None)

    Return additional information about this stream

    This method returns extra information about the channel associated with this stream. See `get_extra_info()` on `SSHClientChannel` for additional information.

  `can_write_eof`()

    Return whether the stream supports `write_eof()`

  `close`()

    Close the channel

    Note

    After this is called, no data can be read or written from any of the streams associated with this channel.

  `drain`()

    Wait until the write buffer on the channel is flushed

    This method is a coroutine which blocks the caller if the stream is currently paused for writing, returning when enough data has been sent on the channel to allow writing to resume. This can be used to avoid buffering an excessive amount of data in the channel’s send buffer.

  `write`(data)

    Write data to the stream

    This method writes bytes or characters to the stream.

    Note

    Unlike traditional `asyncio` stream writers, the data must be supplied as either bytes or a string depending on whether an encoding was specified when the underlying channel was opened.

  `writelines`(list_of_data)

    Write a collection of data to the stream

  `write_eof`()

    Write EOF on the channel

    This method sends an end-of-file indication on the channel, after which no more data can be written.

    Note

    On an `SSHServerChannel` where multiple output streams are created, writing EOF on one stream signals EOF for all of them, since it applies to the channel as a whole.

## SFTP Support

### SFTPClient

class `asyncssh.``SFTPClient`

  SFTP client

  This class represents the client side of an SFTP session. It is started by calling the `start_sftp_client()` method on the `SSHClientConnection` class.

  File transfer methods |
  --- | ---

  `get`(remotepaths, localpath=None, *, preserve=False, recurse=False, follow_symlinks=False, error_handler=None)

    Download remote files

    This method downloads one or more files or directories from the remote system. Either a single remote path or a sequence of remote paths to download can be provided.

    When downloading a single file or directory, the local path can be either the full path to download data into or the path to an existing directory where the data should be placed. In the latter case, the base file name from the remote path will be used as the local name.

    When downloading multiple files, the local path must refer to an existing directory.

    If no local path is provided, the file is downloaded into the current local working directory.

    If preserve is `True`, the access and modification times and permissions of the original file are set on the downloaded file.

    If recurse is `True` and the remote path points at a directory, the entire subtree under that directory is downloaded.

    If follow_symlinks is set to `True`, symbolic links found on the remote system will have the contents of their target downloaded rather than creating a local symbolic link. When using this option during a recursive download, one needs to watch out for links that result in loops.

    If error_handler is specified and an error occurs during the download, this handler will be called with the exception instead of it being raised. This is intended to primarily be used when multiple remote paths are provided or when recurse is set to `True`, to allow error information to be collected without aborting the download of the remaining files. The error handler can raise an exception if it wants the download to completely stop. Otherwise, after an error, the download will continue starting with the next file.

    Parameters:

    - remotepaths (string or bytes, or a sequence of these) – The paths of the remote files or directories to download
    - localpath (string) – (optional) The path of the local file or directory to download into
    - preserve (bool) – (optional) Whether or not to preserve the original file attributes
    - recurse (bool) – (optional) Whether or not to recursively copy directories
    - follow_symlinks (bool) – (optional) Whether or not to follow symbolic links
    - error_handler (callable) – (optional) The function to call when an error occurs

    Raises: | `OSError` if a local file I/O error occurs `SFTPError` if the server returns an error

  `put`(localpaths, remotepath=None, *, preserve=False, recurse=False, follow_symlinks=False, error_handler=None)

    Upload local files

    This method uploads one or more files or directories to the remote system. Either a single local path or a sequence of local paths to upload can be provided.

    When uploading a single file or directory, the remote path can be either the full path to upload data into or the path to an existing directory where the data should be placed. In the latter case, the base file name from the local path will be used as the remote name.

    When uploading multiple files, the remote path must refer to an existing directory.

    If no remote path is provided, the file is uploaded into the current remote working directory.

    If preserve is `True`, the access and modification times and permissions of the original file are set on the uploaded file.

    If recurse is `True` and the local path points at a directory, the entire subtree under that directory is uploaded.

    If follow_symlinks is set to `True`, symbolic links found on the local system will have the contents of their target uploaded rather than creating a remote symbolic link. When using this option during a recursive upload, one needs to watch out for links that result in loops.

    If error_handler is specified and an error occurs during the upload, this handler will be called with the exception instead of it being raised. This is intended to primarily be used when multiple local paths are provided or when recurse is set to `True`, to allow error information to be collected without aborting the upload of the remaining files. The error handler can raise an exception if it wants the upload to completely stop. Otherwise, after an error, the upload will continue starting with the next file.

    Parameters:

    - localpaths (string or bytes, or a sequence of these) – The paths of the local files or directories to upload
    - remotepath (string or bytes) – (optional) The path of the remote file or directory to upload into
    - preserve (bool) – (optional) Whether or not to preserve the original file attributes
    - recurse (bool) – (optional) Whether or not to recursively copy directories
    - follow_symlinks (bool) – (optional) Whether or not to follow symbolic links
    - error_handler (callable) – (optional) The function to call when an error occurs

    Raises: | `OSError` if a local file I/O error occurs `SFTPError` if the server returns an error

  `copy`(srcpaths, dstpath=None, *, preserve=False, recurse=False, follow_symlinks=False, error_handler=None)

    Copy remote files to a new location

    This method copies one or more files or directories on the remote system to a new location. Either a single source path or a sequence of source paths to copy can be provided.

    When copying a single file or directory, the destination path can be either the full path to copy data into or the path to an existing directory where the data should be placed. In the latter case, the base file name from the source path will be used as the destination name.

    When copying multiple files, the destination path must refer to an existing remote directory.

    If no destination path is provided, the file is copied into the current remote working directory.

    If preserve is `True`, the access and modification times and permissions of the original file are set on the copied file.

    If recurse is `True` and the source path points at a directory, the entire subtree under that directory is copied.

    If follow_symlinks is set to `True`, symbolic links found in the source will have the contents of their target copied rather than creating a copy of the symbolic link. When using this option during a recursive copy, one needs to watch out for links that result in loops.

    If error_handler is specified and an error occurs during the copy, this handler will be called with the exception instead of it being raised. This is intended to primarily be used when multiple source paths are provided or when recurse is set to `True`, to allow error information to be collected without aborting the copy of the remaining files. The error handler can raise an exception if it wants the copy to completely stop. Otherwise, after an error, the copy will continue starting with the next file.

    Parameters:

    - srcpaths (string or bytes, or a sequence of these) – The paths of the remote files or directories to copy
    - dstpath (string or bytes) – (optional) The path of the remote file or directory to copy into
    - preserve (bool) – (optional) Whether or not to preserve the original file attributes
    - recurse (bool) – (optional) Whether or not to recursively copy directories
    - follow_symlinks (bool) – (optional) Whether or not to follow symbolic links
    - error_handler (callable) – (optional) The function to call when an error occurs

    Raises: | `OSError` if a local file I/O error occurs `SFTPError` if the server returns an error

  `mget`(remotepaths, localpath=None, *, preserve=False, recurse=False, follow_symlinks=False, error_handler=None)

    Download remote files with glob pattern match

    This method downloads files and directories from the remote system matching one or more glob patterns.

    The arguments to this method are identical to the `get()` method, except that the remote paths specified can contain ‘*’ and ‘?’ wildcard characters.

  `mput`(localpaths, remotepath=None, *, preserve=False, recurse=False, follow_symlinks=False, error_handler=None)

    Upload local files with glob pattern match

    This method uploads files and directories to the remote system matching one or more glob patterns.

    The arguments to this method are identical to the `put()` method, except that the local paths specified can contain ‘*’ and ‘?’ wildcard characters.

  `mcopy`(srcpaths, dstpath=None, *, preserve=False, recurse=False, follow_symlinks=False, error_handler=None)

    Download remote files with glob pattern match

    This method copies files and directories on the remote system matching one or more glob patterns.

    The arguments to this method are identical to the `copy()` method, except that the source paths specified can contain ‘*’ and ‘?’ wildcard characters.

  File access methods |
  --- | ---

  `open`(path, mode='r', attrs=SFTPAttrs(), encoding='utf-8', errors='strict')

    Open a remote file

    This method opens a remote file and returns an `SFTPFile` object which can be used to read and write data and get and set file attributes.

    The path can be either a string or bytes value. If it is a string, it will be encoded using the file encoding specified when the `SFTPClient` was started.

    The following open mode flags are supported:

    > Mode | Description
    > --- | ---
    > FXF_READ | Open the file for reading.
    > FXF_WRITE | Open the file for writing. If both this and FXF_READ are set, open the file for both reading and writing.
    > FXF_APPEND | Force writes to append data to the end of the file regardless of seek position.
    > FXF_CREAT | Create the file if it doesn’t exist. Without this, attempts to open a non-existent file will fail.
    > FXF_TRUNC | Truncate the file to zero length if it already exists.
    > FXF_EXCL | Return an error when trying to open a file which already exists.

    By default, file data is read and written as strings in UTF-8 format with strict error checking, but this can be changed using the `encoding` and `errors` parameters. To read and write data as bytes in binary format, an `encoding` value of `None` can be used.

    Instead of these flags, a Python open mode string can also be provided. Python open modes map to the above flags as follows:

    > Mode | Flags
    > --- | ---
    > r | FXF_READ
    > w | FXF_WRITE | FXF_CREAT | FXF_TRUNC
    > a | FXF_WRITE | FXF_CREAT | FXF_APPEND
    > x | FXF_WRITE | FXF_CREAT | FXF_EXCL
    > r+ | FXF_READ | FXF_WRITE
    > w+ | FXF_READ | FXF_WRITE | FXF_CREAT | FXF_TRUNC
    > a+ | FXF_READ | FXF_WRITE | FXF_CREAT | FXF_APPEND
    > x+ | FXF_READ | FXF_WRITE | FXF_CREAT | FXF_EXCL

    Including a ‘b’ in the mode causes the `encoding` to be set to `None`, forcing all data to be read and written as bytes in binary format.

    The attrs argument is used to set initial attributes of the file if it needs to be created. Otherwise, this argument is ignored.

    Parameters:

    - path (string or bytes) – The name of the remote file to open
    - pflags_or_mode (integer or string) – (optional) The access mode to use for the remote file (see above)
    - attrs (`SFTPAttrs`) – (optional) File attributes to use if the file needs to be created
    - encoding (string) – (optional) The Unicode encoding to use for data read and written to the remote file
    - errors (string) – (optional) The error-handling mode if an invalid Unicode byte sequence is detected, defaulting to ‘strict’ which raises an exception

    Returns: | An `SFTPFile` to use to access the file
    Raises: | `ValueError` if the mode is not valid `SFTPError` if the server returns an error

  `truncate`(path, size)

    Truncate a remote file to the specified size

    This method truncates a remote file to the specified size. If the path provided is a symbolic link, the target of the link will be truncated.

    Parameters:

    - path (string or bytes) – The path of the remote file to be truncated
    - size (integer) – The desired size of the file, in bytes

    Raises: | `SFTPError` if the server returns an error

  `rename`(oldpath, newpath)

    Rename a remote file, directory, or link

    This method renames a remote file, directory, or link.

    Note

    This requests the standard SFTP version of rename which will not overwrite the new path if it already exists. To request POSIX behavior where the new path is removed before the rename, use `posix_rename()`.

    Parameters:

    - oldpath (string or bytes) – The path of the remote file, directory, or link to rename
    - newpath (string or bytes) – The new name for this file, directory, or link

    Raises: | `SFTPError` if the server returns an error

  `posix_rename`(oldpath, newpath)

    Rename a remote file, directory, or link with POSIX semantics

    This method renames a remote file, directory, or link, removing the prior instance of new path if it previously existed.

    This method may not be supported by all SFTP servers.

    Parameters:

    - oldpath (string or bytes) – The path of the remote file, directory, or link to rename
    - newpath (string or bytes) – The new name for this file, directory, or link

    Raises: | `SFTPError` if the server doesn’t support this extension or returns an error

  `remove`(path)

    Remove a remote file

    This method removes a remote file or symbolic link.

    Parameters: | path (string or bytes) – The path of the remote file or link to remove
    Raises: | `SFTPError` if the server returns an error

  `unlink`(path)

    Remove a remote file (see `remove()`)

  `readlink`(path)

    Return the target of a remote symbolic link

    This method returns the target of a symbolic link.

    Parameters: | path (string or bytes) – The path of the remote symbolic link to follow
    Returns: | The target path of the link as a string or bytes
    Raises: | `SFTPError` if the server returns an error

  `symlink`(oldpath, newpath)

    Create a remote symbolic link

    This method creates a symbolic link. The argument order here matches the standard Python `os.symlink()` call. The argument order sent on the wire is automatically adapted depending on the version information sent by the server, as a number of servers (OpenSSH in particular) did not follow the SFTP standard when implementing this call.

    Parameters:

    - oldpath (string or bytes) – The path the link should point to
    - newpath (string or bytes) – The path of where to create the remote symbolic link

    Raises: | `SFTPError` if the server returns an error

  `link`(oldpath, newpath)

    Create a remote hard link

    This method creates a hard link to the remote file specified by oldpath at the location specified by newpath.

    This method may not be supported by all SFTP servers.

    Parameters:

    - oldpath (string or bytes) – The path of the remote file the hard link should point to
    - newpath (string or bytes) – The path of where to create the remote hard link

    Raises: | `SFTPError` if the server doesn’t support this extension or returns an error

  `realpath`(path)

    Return the canonical version of a remote path

    This method returns a canonical version of the requested path.

    Parameters: | path (string or bytes) – (optional) The path of the remote directory to canonicalize
    Returns: | The canonical path as a string or bytes, matching the type used to pass in the path
    Raises: | `SFTPError` if the server returns an error

  File attribute access methods |
  --- | ---

  `stat`(path)

    Get attributes of a remote file or directory, following symlinks

    This method queries the attributes of a remote file or directory. If the path provided is a symbolic link, the returned attributes will correspond to the target of the link.

    Parameters: | path (string or bytes) – The path of the remote file or directory to get attributes for
    Returns: | An `SFTPAttrs` containing the file attributes
    Raises: | `SFTPError` if the server returns an error

  `lstat`(path)

    Get attributes of a remote file, directory, or symlink

    This method queries the attributes of a remote file, directory, or symlink. Unlike `stat()`, this method returns the attributes of a symlink itself rather than the target of that link.

    Parameters: | path (string or bytes) – The path of the remote file, directory, or link to get attributes for
    Returns: | An `SFTPAttrs` containing the file attributes
    Raises: | `SFTPError` if the server returns an error

  `setstat`(path, attrs)

    Set attributes of a remote file or directory

    This method sets attributes of a remote file or directory. If the path provided is a symbolic link, the attributes will be set on the target of the link. A subset of the fields in `attrs` can be initialized and only those attributes will be changed.

    Parameters:

    - path (string or bytes) – The path of the remote file or directory to set attributes for
    - attrs (`SFTPAttrs`) – File attributes to set

    Raises: | `SFTPError` if the server returns an error

  `statvfs`(path)

    Get attributes of a remote file system

    This method queries the attributes of the file system containing the specified path.

    Parameters: | path (string or bytes) – The path of the remote file system to get attributes for
    Returns: | An `SFTPVFSAttrs` containing the file system attributes
    Raises: | `SFTPError` if the server doesn’t support this extension or returns an error

  `chown`(path, uid, gid)

    Change the owner user and group id of a remote file or directory

    This method changes the user and group id of a remote file or directory. If the path provided is a symbolic link, the target of the link will be changed.

    Parameters:

    - path (string or bytes) – The path of the remote file to change
    - uid (integer) – The new user id to assign to the file
    - gid (integer) – The new group id to assign to the file

    Raises: | `SFTPError` if the server returns an error

  `chmod`(path, mode)

    Change the file permissions of a remote file or directory

    This method changes the permissions of a remote file or directory. If the path provided is a symbolic link, the target of the link will be changed.

    Parameters:

    - path (string or bytes) – The path of the remote file to change
    - mode (integer) – The new file permissions, expressed as an integer

    Raises: | `SFTPError` if the server returns an error

  `utime`(path, times=None)

    Change the access and modify times of a remote file or directory

    This method changes the access and modify times of a remote file or directory. If `times` is not provided, the times will be changed to the current time. If the path provided is a symbolic link, the target of the link will be changed.

    Parameters:

    - path (string or bytes) – The path of the remote file to change
    - times (tuple of two integer or float values) – (optional) The new access and modify times, as seconds relative to the UNIX epoch

    Raises: | `SFTPError` if the server returns an error

  `exists`(path)

    Return if the remote path exists and isn’t a broken symbolic link

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `lexists`(path)

    Return if the remote path exists, without following symbolic links

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `getatime`(path)

    Return the last access time of a remote file or directory

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `getmtime`(path)

    Return the last modification time of a remote file or directory

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `getsize`(path)

    Return the size of a remote file or directory

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `isdir`(path)

    Return if the remote path refers to a directory

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `isfile`(path)

    Return if the remote path refers to a regular file

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  `islink`(path)

    Return if the remote path refers to a symbolic link

    Parameters: | path (string or bytes) – The remote path to check
    Raises: | `SFTPError` if the server returns an error

  Directory access methods |
  --- | ---

  `chdir`(path)

    Change the current remote working directory

    Parameters: | path (string or bytes) – The path to set as the new remote working directory
    Raises: | `SFTPError` if the server returns an error

  `getcwd`()

    Return the current remote working directory

    Returns: | The current remote working directory, decoded using the specified path encoding
    Raises: | `SFTPError` if the server returns an error

  `mkdir`(path, attrs=SFTPAttrs())

    Create a remote directory with the specified attributes

    This method creates a new remote directory at the specified path with the requested attributes.

    Parameters:

    - path (string or bytes) – The path of where the new remote directory should be created
    - attrs (`SFTPAttrs`) – (optional) The file attributes to use when creating the directory

    Raises: | `SFTPError` if the server returns an error

  `rmdir`(path)

    Remove a remote directory

    This method removes a remote directory. The directory must be empty for the removal to succeed.

    Parameters: | path (string or bytes) – The path of the remote directory to remove
    Raises: | `SFTPError` if the server returns an error

  `readdir`(path='.')

    Read the contents of a remote directory

    This method reads the contents of a directory, returning the names and attributes of what is contained there. If no path is provided, it defaults to the current remote working directory.

    Parameters: | path (string or bytes) – (optional) The path of the remote directory to read
    Returns: | A list of `SFTPName` entries, with path names matching the type used to pass in the path
    Raises: | `SFTPError` if the server returns an error

  `listdir`(path='.')

    Read the names of the files in a remote directory

    This method reads the names of files and subdirectories in a remote directory. If no path is provided, it defaults to the current remote working directory.

    Parameters: | path (string or bytes) – (optional) The path of the remote directory to read
    Returns: | A list of file/subdirectory names, matching the type used to pass in the path
    Raises: | `SFTPError` if the server returns an error

  `glob`(patterns, error_handler=None)

    Match remote files against glob patterns

    This method matches remote files against one or more glob patterns. Either a single pattern or a sequence of patterns can be provided to match against.

    If error_handler is specified and an error occurs during the match, this handler will be called with the exception instead of it being raised. This is intended to primarily be used when multiple patterns are provided to allow error information to be collected without aborting the match against the remaining patterns. The error handler can raise an exception if it wants to completely abort the match. Otherwise, after an error, the match will continue starting with the next pattern.

    An error will be raised if any of the patterns completely fail to match, and this can either stop the match against the remaining patterns or be handled by the error_handler just like other errors.

    Parameters:

    - patterns (string or bytes, or a sequence of these) – Glob patterns to try and match remote files against
    - error_handler (callable) – (optional) The function to call when an error occurs

    Raises: | `SFTPError` if the server returns an error or no match is found

### SFTPServer

class `asyncssh.``SFTPServer`(conn, chroot=None)

  SFTP server

  Applications should subclass this when implementing an SFTP server. The methods listed below should be implemented to provide the desired application behavior.

  > Note

  > Any method can optionally be defined as a coroutine if that method needs to perform blocking opertions to determine its result.

  The `conn` object provided here refers to the `SSHServerConnection` instance this SFTP server is associated with. It can be queried to determine which user the client authenticated as or to request key and certificate options or permissions which should be applied to this session.

  If the `chroot` argument is specified when this object is created, the default `map_path()` and `reverse_map_path()` methods will enforce a virtual root directory starting in that location, limiting access to only files within that directory tree. This will also affect path names returned by the `realpath()` and `readlink()` methods.

  Path remapping and display methods |
  --- | ---

  `format_longname`(name)

    Format the long name associated with an SFTP name

    This method fills in the `longname` field of a `SFTPName` object. By default, it generates something similar to UNIX “ls -l” output. The `filename` and `attrs` fields of the `SFTPName` should already be filled in before this method is called.

    Parameters: | name (`SFTPName`) – The `SFTPName` instance to format the long name for

  `map_path`(path)

    Map the path requested by the client to a local path

    This method can be overridden to provide a custom mapping from path names requested by the client to paths in the local filesystem. By default, it will enforce a virtual “chroot” if one was specified when this server was created. Otherwise, path names are left unchanged, with relative paths being interpreted based on the working directory of the currently running process.

    Parameters: | path (bytes) – The path name to map
    Returns: | A byte string containing he local path name to operate on

  `reverse_map_path`(path)

    Reverse map a local path into the path reported to the client

    This method can be overridden to provide a custom reverse mapping for the mapping provided by `map_path()`. By default, it hides the portion of the local path associated with the virtual “chroot” if one was specified.

    Parameters: | path (bytes) – The local path name to reverse map
    Returns: | A byte string containing the path name to report to the client

  File access methods |
  --- | ---

  `open`(path, pflags, attrs)

    Open a file to serve to a remote client

    This method returns a file object which can be used to read and write data and get and set file attributes.

    The possible open mode flags and their meanings are:

    > Mode | Description
    > --- | ---
    > FXF_READ | Open the file for reading. If neither FXF_READ nor FXF_WRITE are set, this is the default.
    > FXF_WRITE | Open the file for writing. If both this and FXF_READ are set, open the file for both reading and writing.
    > FXF_APPEND | Force writes to append data to the end of the file regardless of seek position.
    > FXF_CREAT | Create the file if it doesn’t exist. Without this, attempts to open a non-existent file will fail.
    > FXF_TRUNC | Truncate the file to zero length if it already exists.
    > FXF_EXCL | Return an error when trying to open a file which already exists.

    The attrs argument is used to set initial attributes of the file if it needs to be created. Otherwise, this argument is ignored.

    Parameters:

    - path (bytes) – The name of the file to open
    - pflags (integer) – The access mode to use for the file (see above)
    - attrs (`SFTPAttrs`) – File attributes to use if the file needs to be created

    Returns: | A file object to use to access the file
    Raises: | `SFTPError` to return an error to the client

  `close`(file_obj)

    Close an open file or directory

    Parameters: | file_obj (file) – The file or directory object to close
    Raises: | `SFTPError` to return an error to the client

  `read`(file_obj, offset, size)

    Read data from an open file

    Parameters:

    - file_obj (file) – The file to read from
    - offset (integer) – The offset from the beginning of the file to begin reading
    - size (integer) – The number of bytes to read

    Returns: | bytes read from the file
    Raises: | `SFTPError` to return an error to the client

  `write`(file_obj, offset, data)

    Write data to an open file

    Parameters:

    - file_obj (file) – The file to write to
    - offset (integer) – The offset from the beginning of the file to begin writing
    - data (bytes) – The data to write to the file

    Returns: | number of bytes written
    Raises: | `SFTPError` to return an error to the client

  `rename`(oldpath, newpath)

    Rename a file, directory, or link

    This method renames a file, directory, or link.

    Note

    This is a request for the standard SFTP version of rename which will not overwrite the new path if it already exists. The `posix_rename()` method will be called if the client requests the POSIX behavior where an existing instance of the new path is removed before the rename.

    Parameters:

    - oldpath (bytes) – The path of the file, directory, or link to rename
    - newpath (bytes) – The new name for this file, directory, or link

    Raises: | `SFTPError` to return an error to the client

  `posix_rename`(oldpath, newpath)

    Rename a file, directory, or link with POSIX semantics

    This method renames a file, directory, or link, removing the prior instance of new path if it previously existed.

    Parameters:

    - oldpath (bytes) – The path of the file, directory, or link to rename
    - newpath (bytes) – The new name for this file, directory, or link

    Raises: | `SFTPError` to return an error to the client

  `remove`(path)

    Remove a file or symbolic link

    Parameters: | path (bytes) – The path of the file or link to remove
    Raises: | `SFTPError` to return an error to the client

  `readlink`(path)

    Return the target of a symbolic link

    Parameters: | path (bytes) – The path of the symbolic link to follow
    Returns: | A byte string containing the target path of the link
    Raises: | `SFTPError` to return an error to the client

  `symlink`(oldpath, newpath)

    Create a symbolic link

    Parameters:

    - oldpath (bytes) – The path the link should point to
    - newpath (bytes) – The path of where to create the symbolic link

    Raises: | `SFTPError` to return an error to the client

  `link`(oldpath, newpath)

    Create a hard link

    Parameters:

    - oldpath (bytes) – The path of the file the hard link should point to
    - newpath (bytes) – The path of where to create the hard link

    Raises: | `SFTPError` to return an error to the client

  `realpath`(path)

    Return the canonical version of a path

    Parameters: | path (bytes) – The path of the directory to canonicalize
    Returns: | A byte string containing the canonical path
    Raises: | `SFTPError` to return an error to the client

  File attribute access methods |
  --- | ---

  `stat`(path)

    Get attributes of a file or directory, following symlinks

    This method queries the attributes of a file or directory. If the path provided is a symbolic link, the returned attributes should correspond to the target of the link.

    Parameters: | path (bytes) – The path of the remote file or directory to get attributes for
    Returns: | An `SFTPAttrs` or an os.stat_result containing the file attributes
    Raises: | `SFTPError` to return an error to the client

  `lstat`(path)

    Get attributes of a file, directory, or symlink

    This method queries the attributes of a file, directory, or symlink. Unlike `stat()`, this method should return the attributes of a symlink itself rather than the target of that link.

    Parameters: | path (bytes) – The path of the file, directory, or link to get attributes for
    Returns: | An `SFTPAttrs` or an os.stat_result containing the file attributes
    Raises: | `SFTPError` to return an error to the client

  `fstat`(file_obj)

    Get attributes of an open file

    Parameters: | file_obj (file) – The file to get attributes for
    Returns: | An `SFTPAttrs` or an os.stat_result containing the file attributes
    Raises: | `SFTPError` to return an error to the client

  `setstat`(path, attrs)

    Set attributes of a file or directory

    This method sets attributes of a file or directory. If the path provided is a symbolic link, the attributes should be set on the target of the link. A subset of the fields in `attrs` can be initialized and only those attributes should be changed.

    Parameters:

    - path (bytes) – The path of the remote file or directory to set attributes for
    - attrs (`SFTPAttrs`) – File attributes to set

    Raises: | `SFTPError` to return an error to the client

  `fsetstat`(file_obj, attrs)

    Set attributes of an open file

    Parameters: | attrs (`SFTPAttrs`) – File attributes to set on the file
    Raises: | `SFTPError` to return an error to the client

  `statvfs`(path)

    Get attributes of the file system containing a file

    Parameters: | path (bytes) – The path of the file system to get attributes for
    Returns: | An `SFTPVFSAttrs` or an os.statvfs_result containing the file system attributes
    Raises: | `SFTPError` to return an error to the client

  `fstatvfs`(file_obj)

    Return attributes of the file system containing an open file

    Parameters: | file_obj (file) – The open file to get file system attributes for
    Returns: | An `SFTPVFSAttrs` or an os.statvfs_result containing the file system attributes
    Raises: | `SFTPError` to return an error to the client

  Directory access methods |
  --- | ---

  `listdir`(path)

    List the contents of a directory

    Parameters: | path (bytes) – The path of the directory to open
    Returns: | A list of names of files in the directory
    Raises: | `SFTPError` to return an error to the client

  `mkdir`(path, attrs)

    Create a directory with the specified attributes

    Parameters:

    - path (bytes) – The path of where the new directory should be created
    - attrs (`SFTPAttrs`) – The file attributes to use when creating the directory

    Raises: | `SFTPError` to return an error to the client

  `rmdir`(path)

    Remove a directory

    Parameters: | path (bytes) – The path of the directory to remove
    Raises: | `SFTPError` to return an error to the client

  Cleanup methods |
  --- | ---

  `exit`()

    Shut down this SFTP server

### SFTPFile

class `asyncssh.``SFTPFile`

  SFTP client remote file object

  This class represents an open file on a remote SFTP server. It is opened with the `open()` method on the `SFTPClient` class and provides methods to read and write data and get and set attributes on the open file.

  `read`(size=-1, offset=None)

    Read data from the remote file

    This method reads and returns up to `size` bytes of data from the remote file. If size is negative, all data up to the end of the file is returned.

    If offset is specified, the read will be performed starting at that offset rather than the current file position. This argument should be provided if you want to issue parallel reads on the same file, since the file position is not predictable in that case.

    Data will be returned as a string if an encoding was set when the file was opened. Otherwise, data is returned as bytes.

    An empty string or bytes object is returned when at EOF.

    Parameters:

    - size (integer) – The number of bytes to read
    - offset (integer) – (optional) The offset from the beginning of the file to begin reading

    Returns: | data read from the file, as a string or bytes
    Raises: | `ValueError` if the file has been closed `UnicodeDecodeError` if the data can’t be decoded using the requested encoding `SFTPError` if the server returns an error

  `write`(data, offset=None)

    Write data to the remote file

    This method writes the specified data at the current position in the remote file.

    Parameters:

    - data (string or bytes) – The data to write to the file
    - offset (integer) – (optional) The offset from the beginning of the file to begin writing

    If offset is specified, the write will be performed starting at that offset rather than the current file position. This argument should be provided if you want to issue parallel writes on the same file, since the file position is not predictable in that case.

    Returns: | number of bytes written
    Raises: | `ValueError` if the file has been closed `UnicodeEncodeError` if the data can’t be encoded using the requested encoding `SFTPError` if the server returns an error

  `seek`(offset, from_what=SEEK_SET)

    Seek to a new position in the remote file

    This method changes the position in the remote file. The `offset` passed in is treated as relative to the beginning of the file if `from_what` is set to `SEEK_SET` (the default), relative to the current file position if it is set to `SEEK_CUR`, or relative to the end of the file if it is set to `SEEK_END`.

    Parameters:

    - offset (integer) – The amount to seek
    - from_what (integer) – (optional) The reference point to use (SEEK_SET, SEEK_CUR, or SEEK_END)

    Returns: | The new byte offset from the beginning of the file

  `tell`()

    Return the current position in the remote file

    This method returns the current position in the remote file.

    Returns: | The current byte offset from the beginning of the file

  `stat`()

    Return file attributes of the remote file

    This method queries file attributes of the currently open file.

    Returns: | An `SFTPAttrs` containing the file attributes
    Raises: | `SFTPError` if the server returns an error

  `setstat`(attrs)

    Set attributes of the remote file

    This method sets file attributes of the currently open file.

    Parameters: | attrs (`SFTPAttrs`) – File attributes to set on the file
    Raises: | `SFTPError` if the server returns an error

  `statvfs`()

    Return file system attributes of the remote file

    This method queries attributes of the file system containing the currently open file.

    Returns: | An `SFTPVFSAttrs` containing the file system attributes
    Raises: | `SFTPError` if the server doesn’t support this extension or returns an error

  `truncate`(size=None)

    Truncate the remote file to the specified size

    This method changes the remote file’s size to the specified value. If a size is not provided, the current file position is used.

    Parameters: | size (integer) – (optional) The desired size of the file, in bytes
    Raises: | `SFTPError` if the server returns an error

  `chown`(uid, gid)

    Change the owner user and group id of the remote file

    This method changes the user and group id of the currently open file.

    Parameters:

    - uid (integer) – The new user id to assign to the file
    - gid (integer) – The new group id to assign to the file

    Raises: | `SFTPError` if the server returns an error

  `chmod`(mode)

    Change the file permissions of the remote file

    This method changes the permissions of the currently open file.

    Parameters: | mode (integer) – The new file permissions, expressed as an integer
    Raises: | `SFTPError` if the server returns an error

  `utime`(times=None)

    Change the access and modify times of the remote file

    This method changes the access and modify times of the currently open file. If `times` is not provided, the times will be changed to the current time.

    Parameters: | times (tuple of two integer or float values) – (optional) The new access and modify times, as seconds relative to the UNIX epoch
    Raises: | `SFTPError` if the server returns an error

  `fsync`()

    Force the remote file data to be written to disk

  `close`()

    Close the remote file

### SFTPAttrs

class `asyncssh.``SFTPAttrs`

  SFTP file attributes

  SFTPAttrs is a simple record class with the following fields:

  > Field | Description | Type
  > --- | --- | ---
  > size | File size in bytes | uint64
  > uid | User id of file owner | uint32
  > gid | Group id of file owner | uint32
  > permissions | Bit mask of POSIX file permissions, | uint32
  > atime | Last access time, UNIX epoch seconds | uint32
  > mtime | Last modification time, UNIX epoch seconds | uint32

  In addition to the above, an `nlink` field is provided which stores the number of links to this file, but it is not encoded in the SFTP protocol. It’s included here only so that it can be used to create the default `longname` string in `SFTPName` objects.

  Extended attributes can also be added via a field named `extended` which is a list of string name/value pairs.

  When setting attributes using an `SFTPAttrs`, only fields which have been initialized will be changed on the selected file.

### SFTPVFSAttrs

class `asyncssh.``SFTPVFSAttrs`

  SFTP file system attributes

  SFTPVFSAttrs is a simple record class with the following fields:

  > Field | Description | Type
  > --- | --- | ---
  > bsize | File system block size (I/O size) | uint64
  > frsize | Fundamental block size (allocation size) | uint64
  > blocks | Total data blocks (in frsize units) | uint64
  > bfree | Free data blocks | uint64
  > bavail | Available data blocks (for non-root) | uint64
  > files | Total file inodes | uint64
  > ffree | Free file inodes | uint64
  > favail | Available file inodes (for non-root) | uint64
  > fsid | File system id | uint64
  > flags | File system flags (read-only, no-setuid) | uint64
  > namemax | Maximum filename length | uint64

### SFTPName

class `asyncssh.``SFTPName`

  SFTP file name and attributes

  SFTPName is a simple record class with the following fields:

  > Field | Description | Type
  > --- | --- | ---
  > filename | Filename | string or bytes
  > longname | Expanded form of filename & attrs | string or bytes
  > attrs | File attributes | `SFTPAttrs`

  A list of these is returned by `readdir()` in `SFTPClient` when retrieving the contents of a directory.

## Public Key Support

AsyncSSH has extensive public key and certificate support.

Supported public key types include DSA, RSA, and ECDSA. In addition, ed25519 keys are supported if the libnacl package and libsodium library are installed.

Supported certificate types include version 00 certificates for DSA and RSA keys and version 01 certificates for DSA, RSA, ECDSA, and ed25519 keys. Support is also available for the certificate critical options of force-command and source-address and the extensions permit-pty and permit-port-forwarding.

Several public key and certificate formats are supported including PKCS#1 and PKCS#8 DER and PEM, OpenSSH, and RFC4716 formats.

PEM and PKCS#8 password-based encryption of private keys is supported, as is OpenSSH private key encryption when the bcrypt package is installed.

### Specifying private keys

Private keys may be passed into AsyncSSH in a variety of forms. The simplest option is to pass the name of a file containing the list of private keys to read in using `read_private_key_list()`. However, this form can only be used for unencrypted private keys and does not allow any of the private keys to have associated certificates.

An alternate form involves passing in a list of values which can be either a reference to a private key or a tuple containing a reference to a private key and a reference to a matching certificate.

Key references can either be the name of a file to load a key from, a byte string to import it from, or an already loaded `SSHKey` private key. See the function `import_private_key()` for the list of supported private key formats.

Certificate references can be the name of a file to load the certificate from, a byte string to import it from, an already loaded `SSHCertificate`, or `None` if no certificate should be associated with the key.

When a filename is provided as a value in the list, an attempt is made to load a private key from that file and a certificate from a file constructed by appending ‘-cert.pub’ to the end of the name.

Encrypted private keys can be loaded by making an explicit call to `import_private_key()` or `read_private_key()` with the correct passphrase. The resulting `SSHKey` objects can then be included in thie list, each with an optional matching certificate.

### Specifying public keys

Public keys may be passed into AsyncSSH in a variety of forms. The simplest option is to pass the name of a file containing the list of public keys to read in using `read_public_key_list()`.

An alternate form involves passing in a list of values each of which can be either the name of a file to load a key from, a byte string to import it from, or an already loaded `SSHKey` public key. See the function `import_public_key()` for the list of supported public key formats.

### SSHKey

class `asyncssh.``SSHKey`

  Parent class which holds an asymmetric encryption key

  `export_private_key`(format_name, passphrase=None, cipher_name='aes256-cbc', hash_name='sha256', pbe_version=2, rounds=16)

    Export a private key in the requested format

    This function returns this object’s private key encoded in the requested format. If a passphrase is specified, the key will be exported in encrypted form.

    Available formats include:

    > pkcs1-der, pkcs1-pem, pkcs8-der, pkcs8-pem, openssh

    Encryption is supported in pkcs1-pem, pkcs8-der, pkcs8-pem, and openssh formats. For pkcs1-pem, only the cipher can be specified. For pkcs8-der and pkcs-8, cipher, hash and PBE version can be specified. For openssh, cipher and rounds can be specified.

    Available ciphers for pkcs1-pem are:

    > aes128-cbc, aes192-cbc, aes256-cbc, des-cbc, des3-cbc

    Available ciphers for pkcs8-der and pkcs8-pem are:

    > aes128-cbc, aes192-cbc, aes256-cbc, blowfish-cbc, cast128-cbc, des-cbc, des2-cbc, des3-cbc, rc4-40, rc4-128

    Available ciphers for openssh format include the following encryption algorithms.

    Available hashes include:

    > md5, sha1, sha256, sha384, sha512, sha512-224, sha512-256

    Available PBE versions include 1 for PBES1 and 2 for PBES2.

    Not all combinations of cipher, hash, and version are supported.

    The default cipher is aes256. In the pkcs8 formats, the default hash is sha256 and default version is PBES2. In openssh format, the default number of rounds is 16.

    Parameters:

    - format_name (string) – The format to export the key in.
    - passphrase (string) – (optional) A passphrase to encrypt the private key with.
    - cipher_name (string) – (optional) The cipher to use for private key encryption.
    - hash_name (string) – (optional) The hash to use for private key encryption.
    - pbe_version (integer) – (optional) The PBE version to use for private key encryption.
    - rounds (integer) – (optional) The number of KDF rounds to apply to the passphrase.

  `export_public_key`(format_name)

    Export a public key in the requested format

    This function returns this object’s public key encoded in the requested format. Available formats include:

    > pkcs1-der, pkcs1-pem, pkcs8-der, pkcs8-pem, openssh, rfc4716

    Parameters: | format (string) – The format to export the key in.

  `write_private_key`(filename, *args, **kwargs)

    Write a private key to a file in the requested format

    This function is a simple wrapper around export_private_key which writes the exported key data to a file.

    Parameters:

    - filename (string) – The filename to write the private key to.
    - *args,**kwargs – Additional arguments to pass through to `export_private_key()`.

  `write_public_key`(filename, *args, **kwargs)

    Write a public key to a file in the requested format

    This function is a simple wrapper around export_public_key which writes the exported key data to a file.

    Parameters:

    - filename (string) – The filename to write the public key to.
    - *args,**kwargs – Additional arguments to pass through to `export_public_key()`.

### SSHCertificate

class `asyncssh.``SSHCertificate`

  Parent class which holds an SSH certificate

  `validate`(cert_type, principal)

    Validate the certificate type, validity period, and principal

    This method validates that the certificate is of the specified type, that the current time is within the certificate validity period, and that the principal being authenticated is one of the certificate’s valid principals.

    Parameters:

    - cert_type (integer) – The expected certificate type.
    - principal (string) – The principal being authenticated.

    Raises: | `ValueError` if any of the validity checks fail

### import_private_key

`asyncssh.``import_private_key`(data, passphrase=None)

  Import a private key

  This function imports a private key encoded in PKCS#1 or PKCS#8 DER or PEM format or OpenSSH format. Encrypted private keys can be imported by specifying the passphrase needed to decrypt them.

  Parameters:

  - data (bytes or ASCII string) – The data to import.
  - passphrase (string) – (optional) The passphrase to use to decrypt the key.

  Returns: | An `SSHKey` private key

### import_public_key

`asyncssh.``import_public_key`(data)

  Import a public key

  This function imports a public key encoded in OpenSSH, RFC4716, or PKCS#1 or PKCS#8 DER or PEM format.

  Parameters: | data (bytes or ASCII string) – The data to import.
  Returns: | An `SSHKey` public key

### import_certificate

`asyncssh.``import_certificate`(data)

  Import a certificate

  This function imports an SSH certificate in OpenSSH or RFC4716 format.

  Parameters: | data (bytes or ASCII string) – The data to import.
  Returns: | An `SSHCertificate` certificate

### read_private_key

`asyncssh.``read_private_key`(filename, passphrase=None)

  Read a private key from a file

  This function reads a private key from a file. See the function `import_private_key()` for information about the formats supported.

  Parameters:

  - filename (string) – The file to read the key from.
  - passphrase (string) – (optional) The passphrase to use to decrypt the key.

  Returns: | An `SSHKey` private key

### read_public_key

`asyncssh.``read_public_key`(filename)

  Read a public key from a file

  This function reads a public key from a file. See the function `import_public_key()` for information about the formats supported.

  Parameters: | filename (string) – The file to read the key from.
  Returns: | An `SSHKey` public key

### read_certificate

`asyncssh.``read_certificate`(filename)

  Read a certificate from a file

  This function reads an SSH certificate from a file. See the function `import_certificate()` for information about the formats supported.

  Parameters: | filename (string) – The file to read the certificate from.
  Returns: | An `SSHCertificate` certificate

### read_private_key_list

`asyncssh.``read_private_key_list`(filename, passphrase=None)

  Read a list of private keys from a file

  This function reads a list of private keys from a file. See the function `import_private_key()` for information about the formats supported. If any of the keys are encrypted, they must all be encrypted with the same passphrase.

  Parameters:

  - filename (string) – The file to read the keys from.
  - passphrase (string) – (optional) The passphrase to use to decrypt the keys.

  Returns: | A list of `SSHKey` private keys

### read_public_key_list

`asyncssh.``read_public_key_list`(filename)

  Read a list of public keys from a file

  This function reads a list of public keys from a file. See the function `import_public_key()` for information about the formats supported.

  Parameters: | filename (string) – The file to read the keys from.
  Returns: | A list of `SSHKey` public keys

### read_certificate_list

`asyncssh.``read_certificate_list`(filename)

  Read a list of certificates from a file

  This function reads a list of SSH certificates from a file. See the function `import_certificate()` for information about the formats supported.

  Parameters: | filename (string) – The file to read the certificates from.
  Returns: | A list of `SSHCertificate` certificates

## Known hosts

### Specifying known hosts

Known hosts may be passed into AsyncSSH via the `known_hosts` argument to `create_connection()`. This value can be provided in a couple of different forms. The simplest option is to pass the name of a file containing a list of known hosts in OpenSSH known hosts format. AsyncSSH supports both plain and hashed host entries and both regular and negated host patterns in plain entries. It also supports the `@cert-authority` and `@revoked` markers on entries.

Alternately, known hosts can be passed into AsyncSSH as a sequence of three public key lists containing trusted host keys, trusted CA keys, and revoked keys which should no longer be trusted. See Specifying public keys for the allowed form of each of these values.

## Authorized keys

AsyncSSH supports OpenSSH-style authorized_keys files, including the cert-authority option to validate user certificates, enforcement of from and principals options to restrict key matching, enforcement of no-pty, no-port-forwarding, and permitopen options, and support for command and environment options.

### Specifying authorized keys

Authorized keys may be passed into AsyncSSH via the `authorized_client_keys` argument to `create_server()` or by calling `set_authorized_keys()` on the `SSHServerConnection` from within the `begin_auth()` method in `SSHServer`.

Authorized keys can be provided as either the name of a file to read the keys from or an `SSHAuthorizedKeys` object which was previously imported from a string by calling `import_authorized_keys()` or read from a file by calling `read_authorized_keys()`.

### SSHAuthorizedKeys

class `asyncssh.``SSHAuthorizedKeys`

  An SSH authorized keys list

### import_authorized_keys

`asyncssh.``import_authorized_keys`(data)

  Import SSH authorized keys

  This function imports public keys and associated options in OpenSSH authorized keys format.

  Parameters: | data (string) – The key data to import.
  Returns: | An `SSHAuthorizedKeys` object

### read_authorized_keys

`asyncssh.``read_authorized_keys`(filename)

  Read SSH authorized keys from a file

  This function reads public keys and associated options in OpenSSH authorized_keys format from a file.

  Parameters: | filename (string) – The file to read the keys from.
  Returns: | An `SSHAuthorizedKeys` object

## Exceptions

### BreakReceived

exception `asyncssh.``BreakReceived`(msec)

  SSH break request received

  This exception is raised on an SSH server stdin stream when the client sends a break on the channel.

  Parameters: | msec (integer) – The duration of the break in milliseconds

### SignalReceived

exception `asyncssh.``SignalReceived`(signal)

  SSH signal request received

  This exception is raised on an SSH server stdin stream when the client sends a signal on the channel.

  Parameters: | signal (string) – The name of the signal sent by the client

### TerminalSizeChanged

exception `asyncssh.``TerminalSizeChanged`(width, height, pixwidth, pixheight)

  SSH terminal size change notification received

  This exception is raised on an SSH server stdin stream when the client sends a terminal size change on the channel.

  Parameters:

  - width (integer) – The new terminal width
  - height (integer) – The new terminal height
  - pixwidth (integer) – The new terminal width in pixels
  - pixheight (integer) – The new terminal height in pixels

### DisconnectError

exception `asyncssh.``DisconnectError`(code, reason, lang='en-US')

  SSH disconnect error

  This exception is raised when a serious error occurs which causes the SSH connection to be disconnected. Exception codes should be taken from disconnect reason codes.

  Parameters:

  - code (integer) – Disconnect reason, taken from disconnect reason codes
  - reason (string) – A human-readable reason for the disconnect
  - lang (string) – The language the reason is in

### ChannelOpenError

exception `asyncssh.``ChannelOpenError`(code, reason, lang='en-US')

  SSH channel open error

  This exception is raised by connection handlers to report channel open failures.

  Parameters:

  - code (integer) – Channel open failure reason, taken from channel open failure reason codes
  - reason (string) – A human-readable reason for the channel open failure
  - lang (string) – The language the reason is in

### SFTPError

exception `asyncssh.``SFTPError`(code, reason, lang='en-US')

  SFTP error

  This exception is raised when an error occurs while processing an SFTP request. Exception codes should be taken from SFTP error codes.

  Parameters:

  - code (integer) – Disconnect reason, taken from disconnect reason codes
  - reason (string) – A human-readable reason for the disconnect
  - lang (string) – The language the reason is in

### KeyImportError

exception `asyncssh.``KeyImportError`

  Key import error

  This exception is raised by key import functions when the data provided cannot be imported as a valid key.

### KeyExportError

exception `asyncssh.``KeyExportError`

  Key export error

  This exception is raised by key export functions when the requested format is unknown or encryption is requested for a format which doesn’t support it.

### KeyEncryptionError

exception `asyncssh.``KeyEncryptionError`

  Key encryption error

  This exception is raised by key decryption functions when the data provided is not a valid encrypted private key.

## Supported Algorithms

### Key exchange algorithms

The following are the key exchange algorithms currently supported by AsyncSSH:

> curve25519-sha256@libssh.org
> ecdh-sha2-nistp521
> ecdh-sha2-nistp384
> ecdh-sha2-nistp256
> diffie-hellman-group-exchange-sha256
> diffie-hellman-group-exchange-sha1
> diffie-hellman-group14-sha1
> diffie-hellman-group1-sha1

Curve25519 support is only available when the libnacl package and libsodium library are installed.

### Encryption algorithms

The following are the encryption algorithms currently supported by AsyncSSH:

> chacha20-poly1305@openssh.com
> aes256-ctr
> aes192-ctr
> aes128-ctr
> aes256-gcm@openssh.com
> aes128-gcm@openssh.com
> aes256-cbc
> aes192-cbc
> aes128-cbc
> 3des-cbc
> blowfish-cbc
> cast128-cbc
> arcfour256
> arcfour128
> arcfour

Chacha20-poly1305 support is only available when the libnacl package and libsodium library are installed.

### MAC algorithms

The following are the MAC algorithms currently supported by AsyncSSH:

> hmac-sha2-256-etm@openssh.com
> hmac-sha2-512-etm@openssh.com
> hmac-sha1-etm@openssh.com
> hmac-md5-etm@openssh.com
> hmac-sha2-256-96-etm@openssh.com
> hmac-sha2-512-96-etm@openssh.com
> hmac-sha1-96-etm@openssh.com
> hmac-md5-96-etm@openssh.com
> hmac-sha2-256
> hmac-sha2-512
> hmac-sha1
> hmac-md5
> hmac-sha2-256-96
> hmac-sha2-512-96
> hmac-sha1-96
> hmac-md5-96

### Compression algorithms

The following are the compression algorithms currently supported by AsyncSSH:

> zlib@openssh.com
> zlib
> none

### Public key & certificate algorithms

The following are the public key and certificate algorithms currently supported by AsyncSSH:

> ssh-ed25519-cert-v01@openssh.com
> ecdsa-sha2-nistp521-cert-v01@openssh.com
> ecdsa-sha2-nistp384-cert-v01@openssh.com
> ecdsa-sha2-nistp256-cert-v01@openssh.com
> ssh-rsa-cert-v01@openssh.com
> ssh-rsa-cert-v00@openssh.com
> ssh-dss-cert-v01@openssh.com
> ssh-dss-cert-v00@openssh.com
> ssh-ed25519
> ecdsa-sha2-nistp521
> ecdsa-sha2-nistp384
> ecdsa-sha2-nistp256
> ssh-rsa
> ssh-dss

Ed25519 support is only available when the libnacl package and libsodium library are installed.

## Constants

### Certificate types

The following values can be specified as certificate types:

> CERT_TYPE_USER
> CERT_TYPE_HOST

### Disconnect reasons

The following values defined in section 11.1 of RFC 4253#section-11.1 can be specified as disconnect reason codes:

> DISC_HOST_NOT_ALLOWED_TO_CONNECT
> DISC_PROTOCOL_ERROR
> DISC_KEY_EXCHANGE_FAILED
> DISC_RESERVED
> DISC_MAC_ERROR
> DISC_COMPRESSION_ERROR
> DISC_SERVICE_NOT_AVAILABLE
> DISC_PROTOCOL_VERSION_NOT_SUPPORTED
> DISC_HOST_KEY_NOT_VERIFYABLE
> DISC_CONNECTION_LOST
> DISC_BY_APPLICATION
> DISC_TOO_MANY_CONNECTIONS
> DISC_AUTH_CANCELLED_BY_USER
> DISC_NO_MORE_AUTH_METHODS_AVAILABLE
> DISC_ILLEGAL_USER_NAME

### Channel open failure reasons

The following values defined in section 5.1 of RFC 4254#section-5.1 can be specified as channel open failure reason codes:

> OPEN_ADMINISTRATIVELY_PROHIBITED
> OPEN_CONNECT_FAILED
> OPEN_UNKNOWN_CHANNEL_TYPE
> OPEN_RESOURCE_SHORTAGE
> OPEN_REQUEST_PTY_FAILED
> OPEN_REQUEST_SESSION_FAILED

### SFTP error codes

The following values defined in the SSH File Transfer Internet Draft can be specified as SFTP error codes:

> FX_OK
> FX_EOF
> FX_NO_SUCH_FILE
> FX_PERMISSION_DENIED
> FX_FAILURE
> FX_BAD_MESSAGE
> FX_NO_CONNECTION
> FX_CONNECTION_LOST
> FX_OP_UNSUPPORTED

### Extended data types

The following values defined in section 5.2 of RFC 4254#section-5.2 can be specified as SSH extended channel data types:

> EXTENDED_DATA_STDERR

### POSIX terminal modes

The following values defined in section 8 of RFC 4254#section-8 can be specified as PTY mode opcodes:

> PTY_OP_END
> PTY_VINTR
> PTY_VQUIT
> PTY_VERASE
> PTY_VKILL
> PTY_VEOF
> PTY_VEOL
> PTY_VEOL2
> PTY_VSTART
> PTY_VSTOP
> PTY_VSUSP
> PTY_VDSUSP
> PTY_VREPRINT
> PTY_WERASE
> PTY_VLNEXT
> PTY_VFLUSH
> PTY_VSWTCH
> PTY_VSTATUS
> PTY_VDISCARD
> PTY_IGNPAR
> PTY_PARMRK
> PTY_INPCK
> PTY_ISTRIP
> PTY_INLCR
> PTY_IGNCR
> PTY_ICRNL
> PTY_IUCLC
> PTY_IXON
> PTY_IXANY
> PTY_IXOFF
> PTY_IMAXBEL
> PTY_ISIG
> PTY_ICANON
> PTY_XCASE
> PTY_ECHO
> PTY_ECHOE
> PTY_ECHOK
> PTY_ECHONL
> PTY_NOFLSH
> PTY_TOSTOP
> PTY_IEXTEN
> PTY_ECHOCTL
> PTY_ECHOKE
> PTY_PENDIN
> PTY_OPOST
> PTY_OLCUC
> PTY_ONLCR
> PTY_OCRNL
> PTY_ONOCR
> PTY_ONLRET
> PTY_CS7
> PTY_CS8
> PTY_PARENB
> PTY_PARODD
> PTY_OP_ISPEED
> PTY_OP_OSPEED