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()
, create_connection()
, and create_unix_connection()
on the
SSHClientConnection
object. The client can also set up listeners on
remote TCP ports and UNIX domain sockets by calling create_server()
and create_unix_server()
. All of these methods take
session_factory
arguments that return SSHClientSession
,
SSHTCPSession
, or SSHUNIXSession
objects used to manage
the channels once they are open. Alternately, channels can be opened using
open_session()
,
open_connection()
, or
open_unix_connection()
,
which return SSHReader
and SSHWriter
objects that can be
used to perform I/O on the channel. The methods start_server()
and start_unix_server()
can be used to set up listeners on
remote TCP ports or UNIX domain sockets and get back these SSHReader
and SSHWriter
objects in a callback when new connections are opened.
SSH client sessions can also be opened by calling create_process()
. This returns a SSHClientProcess
object which has members stdin
, stdout
, and stderr
which are
SSHReader
and SSHWriter
objects. This API also makes
it very easy to redirect input and output from the remote process to local
files, pipes, sockets, or other SSHReader
and SSHWriter
objects. In cases where you just want to run a remote process to completion
and get back an object containing captured output and exit status, the
run()
method can be used. It returns an
SSHCompletedProcess
with the results of the run, or can be set up
to raise ProcessError
if the process exits with a non-zero exit
status. It can also raise TimeoutError
if a specified timeout
expires before the process exits.
The client can also set up TCP port forwarding by calling
forward_local_port()
or
forward_remote_port()
and
UNIX domain socket forwarding by calling forward_local_path()
or forward_remote_path()
. Mixed forwarding from a TCP port
to a UNIX domain socket or vice-versa can be set up using the functions
forward_local_port_to_path()
,
forward_local_path_to_port()
,
forward_remote_port_to_path()
, and
forward_remote_path_to_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.
Dynamic TCP port forwarding can be set up by calling forward_socks()
. The SOCKS listener set up by
AsyncSSH on the requested port accepts SOCKS connect requests and is
compatible with SOCKS versions 4, 4a, and 5.
When an SSH server receives a new connection and authentication is successful,
handlers such as session_requested()
,
connection_requested()
,
unix_connection_requested()
,
server_requested()
, and
unix_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.
To better support interactive server applications, AsyncSSH defaults to
providing echoing of input and basic line editing capabilities when an
inbound SSH session requests a pseudo-terminal. This behavior can be
disabled by setting the line_editor
argument to False
when
starting up an SSH server. When this feature is enabled, server sessions
can enable or disable line mode using the set_line_mode()
method of SSHLineEditorChannel
.
They can also enable or disable input echoing using the set_echo()
method. Handling of specific keys during
line editing can be customized using the register_key()
and unregister_key()
methods.
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 Exceptions, supported algorithms can be found under Supported Algorithms, and some useful constants can be found under Constants.
Main Functions¶
connect¶
- asyncssh.connect(host='', port=(), *, tunnel=(), family=(), flags=0, local_addr=(), sock=None, config=(), options=None, **kwargs)[source]¶
Make 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:
The connection is established and an instance of
SSHClientConnection
is created to represent it.The
client_factory
is called without arguments and should return an instance ofSSHClient
or a subclass.The client object is tied to the connection and its
connection_made()
method is called.The SSH handshake and authentication process is initiated, calling methods on the client object if needed.
When authentication completes successfully, the client’s
auth_completed()
method is called.The coroutine returns the
SSHClientConnection
. 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.
- Parameters
host (
str
) – (optional) The hostname or address to connect to.port (
int
) – (optional) The port number to connect to. If not specified, the default SSH port is used.tunnel (
SSHClientConnection
orstr
) –(optional) An existing SSH client connection that this new connection should be tunneled over. If set, a direct TCP/IP tunnel will be opened over this connection to the requested host and port rather than connecting directly via TCP. A string of the form [user@]host[:port] may also be specified, in which case a connection will first be made to that host and it will then be used as a tunnel.
Note
When specifying tunnel as a string, any config options in the call will apply only when opening the connection inside the tunnel. The tunnel itself will be opened with default configuration settings or settings in the default config file. To get more control of config settings used to open the tunnel,
connect()
can be called explicitly, and the resulting client connection can be passed as the tunnel argument.family (
socket.AF_UNSPEC
,socket.AF_INET
, orsocket.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 addresslocal_addr (tuple of
str
andint
) – (optional) The host and port to bind the socket to before connectingsock (
socket.socket
orNone
) – (optional) An existing already-connected socket to run SSH over, instead of opening up a new connection. When this is specified, none of host, port family, flags, or local_addr should be specified.config (
list
ofstr
) – (optional) Paths to OpenSSH client configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. If no paths are specified and no config paths were set when constructing theoptions
argument (if any), an attempt will be made to load the configuration from the file.ssh/config
. If this argument is explicitly set toNone
, no new configuration files will be loaded, but any configuration loaded when constructing theoptions
argument will still apply. See Supported client config options for details on what configuration options are currently supported.options (
SSHClientConnectionOptions
) – (optional) Options to use when establishing the SSH client connection. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
connect_reverse¶
- asyncssh.connect_reverse(host='', port=(), *, tunnel=(), family=(), flags=0, local_addr=(), sock=None, config=(), options=None, **kwargs)[source]¶
Create a reverse direction SSH connection
This function is a coroutine which behaves similar to
connect()
, making an outbound TCP connection to a remote server. However, instead of starting up an SSH client which runs on that outbound connection, this function starts up an SSH server, expecting the remote system to start up a reverse-direction SSH client.Arguments to this function are the same as
connect()
, except that theoptions
are of typeSSHServerConnectionOptions
instead ofSSHClientConnectionOptions
.- Parameters
host (
str
) – (optional) The hostname or address to connect to.port (
int
) – (optional) The port number to connect to. If not specified, the default SSH port is used.tunnel (
SSHClientConnection
orstr
) –(optional) An existing SSH client connection that this new connection should be tunneled over. If set, a direct TCP/IP tunnel will be opened over this connection to the requested host and port rather than connecting directly via TCP. A string of the form [user@]host[:port] may also be specified, in which case a connection will first be made to that host and it will then be used as a tunnel.
Note
When specifying tunnel as a string, any config options in the call will apply only when opening the connection inside the tunnel. The tunnel itself will be opened with default configuration settings or settings in the default config file. To get more control of config settings used to open the tunnel,
connect()
can be called explicitly, and the resulting client connection can be passed as the tunnel argument.family (
socket.AF_UNSPEC
,socket.AF_INET
, orsocket.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 addresslocal_addr (tuple of
str
andint
) – (optional) The host and port to bind the socket to before connectingsock (
socket.socket
orNone
) – (optional) An existing already-connected socket to run SSH over, instead of opening up a new connection. When this is specified, none of host, port family, flags, or local_addr should be specified.config (
list
ofstr
) – (optional) Paths to OpenSSH server configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. By default, no OpenSSH configuration files will be loaded. See Supported server config options for details on what configuration options are currently supported.options (
SSHServerConnectionOptions
) – (optional) Options to use when starting the reverse-direction SSH server. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
listen¶
- asyncssh.listen(host='', port=(), *, tunnel=(), family=(), flags=AddressInfo.AI_PASSIVE, backlog=100, sock=None, reuse_address=False, reuse_port=False, acceptor=None, error_handler=None, config=(), options=None, **kwargs)[source]¶
Start an SSH server
This function is a coroutine which can be run to create an SSH server listening on the specified host and port. The return value is an
SSHAcceptor
which can be used to shut down the listener.- Parameters
host (
str
) – (optional) The hostname or address to listen on. If not specified, listeners are created for all addresses.port (
int
) – (optional) The port number to listen on. If not specified, the default SSH port is used.tunnel (
SSHClientConnection
orstr
) –(optional) An existing SSH client connection that this new listener should be forwarded over. If set, a remote TCP/IP listener will be opened on this connection on the requested host and port rather than listening directly via TCP. A string of the form [user@]host[:port] may also be specified, in which case a connection will first be made to that host and it will then be used as a tunnel.
Note
When specifying tunnel as a string, any config options in the call will apply only when opening the connection inside the tunnel. The tunnel itself will be opened with default configuration settings or settings in the default config file. To get more control of config settings used to open the tunnel,
connect()
can be called explicitly, and the resulting client connection can be passed as the tunnel argument.family (
socket.AF_UNSPEC
,socket.AF_INET
, orsocket.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 hostbacklog (
int
) – (optional) The maximum number of queued connections allowed on listenerssock (
socket.socket
orNone
) – (optional) A pre-existing socket to use instead of creating and binding a new socket. When this is specified, host and port should not be specified.reuse_address (
bool
) – (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 toTrue
on UNIX.reuse_port (
bool
) – (optional) Whether or not to allow this socket to be bound to the same port other existing sockets are bound to, so long as they all set this flag when being created. If not specified, the default is to not allow this. This option is not supported on Windows or Python versions prior to 3.4.4.acceptor (
callable
or coroutine) – (optional) Acallable
or coroutine which will be called when the SSH handshake completes on an accepted connection, taking theSSHServerConnection
as an argument.error_handler (
callable
) – (optional) Acallable
which will be called whenever the SSH handshake fails on an accepted connection. It is called with the failedSSHServerConnection
and an exception object describing the failure. If not specified, failed handshakes result in the connection object being silently cleaned up.config (
list
ofstr
) – (optional) Paths to OpenSSH server configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. By default, no OpenSSH configuration files will be loaded. See Supported server config options for details on what configuration options are currently supported.options (
SSHServerConnectionOptions
) – (optional) Options to use when accepting SSH server connections. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
listen_reverse¶
- asyncssh.listen_reverse(host='', port=(), *, tunnel=(), family=(), flags=AddressInfo.AI_PASSIVE, backlog=100, sock=None, reuse_address=False, reuse_port=False, acceptor=None, error_handler=None, config=(), options=None, **kwargs)[source]¶
Create a reverse-direction SSH listener
This function is a coroutine which behaves similar to
listen()
, creating a listener which accepts inbound connections on the specified host and port. However, instead of starting up an SSH server on each inbound connection, it starts up a reverse-direction SSH client, expecting the remote system making the connection to start up a reverse-direction SSH server.Arguments to this function are the same as
listen()
, except that theoptions
are of typeSSHClientConnectionOptions
instead ofSSHServerConnectionOptions
.The return value is an
SSHAcceptor
which can be used to shut down the reverse listener.- Parameters
host (
str
) – (optional) The hostname or address to listen on. If not specified, listeners are created for all addresses.port (
int
) – (optional) The port number to listen on. If not specified, the default SSH port is used.tunnel (
SSHClientConnection
orstr
) –(optional) An existing SSH client connection that this new listener should be forwarded over. If set, a remote TCP/IP listener will be opened on this connection on the requested host and port rather than listening directly via TCP. A string of the form [user@]host[:port] may also be specified, in which case a connection will first be made to that host and it will then be used as a tunnel.
Note
When specifying tunnel as a string, any config options in the call will apply only when opening the connection inside the tunnel. The tunnel itself will be opened with default configuration settings or settings in the default config file. To get more control of config settings used to open the tunnel,
connect()
can be called explicitly, and the resulting client connection can be passed as the tunnel argument.family (
socket.AF_UNSPEC
,socket.AF_INET
, orsocket.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 hostbacklog (
int
) – (optional) The maximum number of queued connections allowed on listenerssock (
socket.socket
orNone
) – (optional) A pre-existing socket to use instead of creating and binding a new socket. When this is specified, host and port should notreuse_address (
bool
) – (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 toTrue
on UNIX.reuse_port (
bool
) – (optional) Whether or not to allow this socket to be bound to the same port other existing sockets are bound to, so long as they all set this flag when being created. If not specified, the default is to not allow this. This option is not supported on Windows or Python versions prior to 3.4.4.acceptor (
callable
or coroutine) – (optional) Acallable
or coroutine which will be called when the SSH handshake completes on an accepted connection, taking theSSHClientConnection
as an argument.error_handler (
callable
) – (optional) Acallable
which will be called whenever the SSH handshake fails on an accepted connection. It is called with the failedSSHClientConnection
and an exception object describing the failure. If not specified, failed handshakes result in the connection object being silently cleaned up.config (
list
ofstr
) – (optional) Paths to OpenSSH client configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. If no paths are specified and no config paths were set when constructing theoptions
argument (if any), an attempt will be made to load the configuration from the file.ssh/config
. If this argument is explicitly set toNone
, no new configuration files will be loaded, but any configuration loaded when constructing theoptions
argument will still apply. See Supported client config options for details on what configuration options are currently supported.options (
SSHClientConnectionOptions
) – (optional) Options to use when starting reverse-direction SSH clients. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
run_client¶
- asyncssh.run_client(sock, config=(), options=None, **kwargs)[source]¶
Start an SSH client connection on an already-connected socket
This function is a coroutine which starts an SSH client on an existing already-connected socket. It can be used instead of
connect()
when a socket is connected outside of asyncio.- Parameters
sock (
socket.socket
) – An existing already-connected socket to run an SSH client on, instead of opening up a new connection.config (
list
ofstr
) – (optional) Paths to OpenSSH client configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. If no paths are specified and no config paths were set when constructing theoptions
argument (if any), an attempt will be made to load the configuration from the file.ssh/config
. If this argument is explicitly set toNone
, no new configuration files will be loaded, but any configuration loaded when constructing theoptions
argument will still apply. See Supported client config options for details on what configuration options are currently supported.options (
SSHClientConnectionOptions
) – (optional) Options to use when establishing the SSH client connection. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
run_server¶
- asyncssh.run_server(sock, config=(), options=None, **kwargs)[source]¶
Start an SSH server connection on an already-connected socket
This function is a coroutine which starts an SSH server on an existing already-connected TCP socket. It can be used instead of
listen()
when connections are accepted outside of asyncio.- Parameters
sock (
socket.socket
) – An existing already-connected socket to run SSH over, instead of opening up a new connection.config (
list
ofstr
) – (optional) Paths to OpenSSH server configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. By default, no OpenSSH configuration files will be loaded. See Supported server config options for details on what configuration options are currently supported.options (
SSHServerConnectionOptions
) – (optional) Options to use when starting the reverse-direction SSH server. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
create_connection¶
- async asyncssh.create_connection(client_factory, host='', port=(), **kwargs)[source]¶
Create an SSH client connection
This is a coroutine which wraps around
connect()
, providing backward compatibility with older AsyncSSH releases. The only differences are that theclient_factory
argument is the first positional argument in this call rather than being a keyword argument or specified via anSSHClientConnectionOptions
object and the return value is a tuple of anSSHClientConnection
andSSHClient
rather than just the connection, mirroringasyncio.AbstractEventLoop.create_connection()
.- Returns
An
SSHClientConnection
andSSHClient
create_server¶
- asyncssh.create_server(server_factory, host='', port=(), **kwargs)[source]¶
Create an SSH server
This is a coroutine which wraps around
listen()
, providing backward compatibility with older AsyncSSH releases. The only difference is that theserver_factory
argument is the first positional argument in this call rather than being a keyword argument or specified via anSSHServerConnectionOptions
object, mirroringasyncio.AbstractEventLoop.create_server()
.
get_server_host_key¶
- async asyncssh.get_server_host_key(host='', port=(), *, tunnel=(), proxy_command=(), family=(), flags=0, local_addr=(), sock=None, client_version=(), kex_algs=(), server_host_key_algs=(), config=(), options=None)[source]¶
Retrieve an SSH server’s host key
This is a coroutine which can be run to connect to an SSH server and return the server host key presented during the SSH handshake.
A list of server host key algorithms can be provided to specify which host key types the server is allowed to choose from. If the key exchange is successful, the server host key sent during the handshake is returned.
Note
Not all key exchange methods involve the server presenting a host key. If something like GSS key exchange is used without a server host key, this method may return
None
even when the handshake completes.- Parameters
host (
str
) – (optional) The hostname or address to connect toport (
int
) – (optional) The port number to connect to. If not specified, the default SSH port is used.tunnel (
SSHClientConnection
orstr
) –(optional) An existing SSH client connection that this new connection should be tunneled over. If set, a direct TCP/IP tunnel will be opened over this connection to the requested host and port rather than connecting directly via TCP. A string of the form [user@]host[:port] may also be specified, in which case a connection will first be made to that host and it will then be used as a tunnel.
Note
When specifying tunnel as a string, any config options in the call will apply only when opening the connection inside the tunnel. The tunnel itself will be opened with default configuration settings or settings in the default config file. To get more control of config settings used to open the tunnel,
connect()
can be called explicitly, and the resulting client connection can be passed as the tunnel argument.proxy_command (
str
orlist
ofstr
) – (optional) A string or list of strings specifying a command and arguments to run to make a connection to the SSH server. Data will be forwarded to this process over stdin/stdout instead of opening a TCP connection. If specified as a string, standard shell quoting will be applied when splitting the command and its arguments.family (
socket.AF_UNSPEC
,socket.AF_INET
, orsocket.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 addresslocal_addr (tuple of
str
andint
) – (optional) The host and port to bind the socket to before connectingsock (
socket.socket
orNone
) – (optional) An existing already-connected socket to run SSH over, instead of opening up a new connection. When this is specified, none of host, port family, flags, or local_addr should be specified.client_version (
str
) – (optional) An ASCII string to advertise to the SSH server as the version of this client, defaulting to'AsyncSSH'
and its version number.kex_algs (
str
orlist
ofstr
) – (optional) A list of allowed key exchange algorithms in the SSH handshake, taken from key exchange algorithmsserver_host_key_algs (
str
orlist
ofstr
) – (optional) A list of server host key algorithms to allow during the SSH handshake, taken from server host key algorithms.config (
list
ofstr
) – (optional) Paths to OpenSSH client configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. If no paths are specified and no config paths were set when constructing theoptions
argument (if any), an attempt will be made to load the configuration from the file.ssh/config
. If this argument is explicitly set toNone
, no new configuration files will be loaded, but any configuration loaded when constructing theoptions
argument will still apply. See Supported client config options for details on what configuration options are currently supported.options (
SSHClientConnectionOptions
) – (optional) Options to use when establishing the SSH client connection used to retrieve the server host key. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
get_server_auth_methods¶
- async asyncssh.get_server_auth_methods(host='', port=(), username=(), *, tunnel=(), proxy_command=(), family=(), flags=0, local_addr=(), sock=None, client_version=(), kex_algs=(), server_host_key_algs=(), config=(), options=None)[source]¶
Retrieve an SSH server’s allowed auth methods
This is a coroutine which can be run to connect to an SSH server and return the auth methods available to authenticate to it.
Note
The key exchange with the server must complete successfully before the list of available auth methods can be returned, so be sure to specify any arguments needed to complete the key exchange. Also, auth methods may vary by user, so you may want to specify the specific user you would like to get auth methods for.
- Parameters
host (
str
) – (optional) The hostname or address to connect toport (
int
) – (optional) The port number to connect to. If not specified, the default SSH port is used.username – (optional) Username to authenticate as on the server. If not specified, the currently logged in user on the local machine will be used.
tunnel (
SSHClientConnection
orstr
) –(optional) An existing SSH client connection that this new connection should be tunneled over. If set, a direct TCP/IP tunnel will be opened over this connection to the requested host and port rather than connecting directly via TCP. A string of the form [user@]host[:port] may also be specified, in which case a connection will first be made to that host and it will then be used as a tunnel.
Note
When specifying tunnel as a string, any config options in the call will apply only when opening the connection inside the tunnel. The tunnel itself will be opened with default configuration settings or settings in the default config file. To get more control of config settings used to open the tunnel,
connect()
can be called explicitly, and the resulting client connection can be passed as the tunnel argument.proxy_command (
str
orlist
ofstr
) – (optional) A string or list of strings specifying a command and arguments to run to make a connection to the SSH server. Data will be forwarded to this process over stdin/stdout instead of opening a TCP connection. If specified as a string, standard shell quoting will be applied when splitting the command and its arguments.family (
socket.AF_UNSPEC
,socket.AF_INET
, orsocket.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 addresslocal_addr (tuple of
str
andint
) – (optional) The host and port to bind the socket to before connectingsock (
socket.socket
orNone
) – (optional) An existing already-connected socket to run SSH over, instead of opening up a new connection. When this is specified, none of host, port family, flags, or local_addr should be specified.client_version (
str
) – (optional) An ASCII string to advertise to the SSH server as the version of this client, defaulting to'AsyncSSH'
and its version number.kex_algs (
str
orlist
ofstr
) – (optional) A list of allowed key exchange algorithms in the SSH handshake, taken from key exchange algorithmsserver_host_key_algs (
str
orlist
ofstr
) – (optional) A list of server host key algorithms to allow during the SSH handshake, taken from server host key algorithms.config (
list
ofstr
) – (optional) Paths to OpenSSH client configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options. If no paths are specified and no config paths were set when constructing theoptions
argument (if any), an attempt will be made to load the configuration from the file.ssh/config
. If this argument is explicitly set toNone
, no new configuration files will be loaded, but any configuration loaded when constructing theoptions
argument will still apply. See Supported client config options for details on what configuration options are currently supported.options (
SSHClientConnectionOptions
) – (optional) Options to use when establishing the SSH client connection used to retrieve the server host key. These options can be specified either through this parameter or as direct keyword arguments to this function.
- Returns
scp¶
- async asyncssh.scp(srcpaths, dstpath=None, *, preserve=False, recurse=False, block_size=16384, progress_handler=None, error_handler=None, **kwargs)[source]¶
Copy files using SCP
This function is a coroutine which copies one or more files or directories using the SCP protocol. Source and destination paths can be
str
orbytes
values to reference local files or can be a tuple of the form(conn, path)
whereconn
is an openSSHClientConnection
to reference files and directories on a remote system.For convenience, a host name or tuple of the form
(host, port)
can be provided in place of theSSHClientConnection
to request that a new SSH connection be opened to a host using default connect arguments. Astr
orbytes
value of the form'host:path'
may also be used in place of the(conn, path)
tuple to make a new connection to the requested host on the default SSH port.Either a single source path or a sequence of source paths can be provided, and each path can contain ‘*’ and ‘?’ wildcard characters which can be used to match multiple source files or directories.
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 a directory. If it doesn’t already exist, a directory will be created with that name.
If the destination path is an
SSHClientConnection
without a path or the path provided is empty, files are copied into the default destination working directory.If preserve is
True
, the access and modification times and permissions of the original files and directories are set on the copied files. However, do to the timing of when this information is sent, the preserved access time will be what was set on the source file before the copy begins. So, the access time on the source file will no longer match the destination after the transfer completes.If recurse is
True
and the source path points at a directory, the entire subtree under that directory is copied.Symbolic links found on the source will have the contents of their target copied rather than creating a destination symbolic link. When using this option during a recursive copy, one needs to watch out for links that result in loops. SCP does not provide a mechanism for preserving links. If you need this, consider using SFTP instead.
The block_size value controls the size of read and write operations issued to copy the files. It defaults to 16 KB.
If progress_handler is specified, it will be called after each block of a file is successfully copied. The arguments passed to this handler will be the relative path of the file being copied, bytes copied so far, and total bytes in the file being copied. If multiple source paths are provided or recurse is set to
True
, the progress_handler will be called consecutively on each file being copied.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.If any other keyword arguments are specified, they will be passed to the AsyncSSH connect() call when attempting to open any new SSH connections needed to perform the file transfer.
- Parameters
srcpaths – The paths of the source files or directories to copy
dstpath – (optional) The path of the destination file or directory to copy into
preserve (
bool
) – (optional) Whether or not to preserve the original file attributesrecurse (
bool
) – (optional) Whether or not to recursively copy directoriesblock_size (
int
) – (optional) The block size to use for file reads and writesprogress_handler (
callable
) – (optional) The function to call to report copy progresserror_handler (
callable
) – (optional) The function to call when an error occurs
- Raises
OSError
if a local file I/O error occursSFTPError
if the server returns an errorValueError
if both source and destination are local
Main Classes¶
SSHClient¶
- class asyncssh.SSHClient[source]¶
SSH client protocol handler
Applications may subclass this when implementing an SSH client to receive callbacks when certain events occur on the SSH connection.
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/orpublic_key_auth_requested()
can be defined. Keyboard-interactive authentication is also supported viakbdint_auth_requested()
andkbdint_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 eitherpassword_changed()
orpassword_change_failed()
depending on whether the password change is successful.Note
The authentication callbacks described here can be defined as coroutines. However, they may be cancelled if they are running when the SSH connection is closed by the server. If they attempt to catch the CancelledError exception to perform cleanup, they should make sure to re-raise it to allow AsyncSSH to finish its own cleanup.
General connection handlers
- connection_made(conn)[source]¶
Called when a connection is made
This method is called as soon as the TCP connection completes. The
conn
parameter should be stored if needed for later use.- Parameters
conn (
SSHClientConnection
) – The connection which was successfully opened
Host key validation handlers
- validate_host_public_key(host, addr, port, key)[source]¶
Return whether key is an authorized key for this host
Server host key validation can be supported by passing known host keys in the
known_hosts
argument ofcreate_connection()
. 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 returnTrue
if the specified key is a valid host key for the server being connected to.By default, this method returns
False
for all host keys.Note
This function only needs to report whether the public key provided is a valid key for this host. If it is, AsyncSSH will verify that the server possesses the corresponding private key before allowing the validation to succeed.
- validate_host_ca_key(host, addr, port, key)[source]¶
Return whether key is an authorized CA key for this host
Server host certificate validation can be supported by passing known host CA keys in the
known_hosts
argument ofcreate_connection()
. 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 returnTrue
if the specified key is a valid certificate authority key for the server being connected to.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 host. If it is, AsyncSSH will verify that the certificate is valid, that the host is one of the valid principals for the certificate, and that the server possesses the private key corresponding to the public key in the certificate before allowing the validation to succeed.
- Parameters
- Returns
A
bool
indicating if the specified key is a valid CA key for the target host
General authentication handlers
- auth_completed()[source]¶
Authentication was completed successfully
This method is called when authentication has completed successfully. Applications may use this method to create whatever client sessions and direct TCP/IP or UNIX domain connections are needed and/or set up listeners for incoming TCP/IP or UNIX domain connections coming from the server. However,
create_connection()
now blocks until authentication is complete, so any code which wishes to use the SSH connection can simply follow that call and doesn’t need to be performed in a callback.
Public key authentication handlers
- public_key_auth_requested()[source]¶
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()[source]¶
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)[source]¶
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
- Returns
A tuple of two strings containing the old and new passwords or
NotImplemented
if password changes aren’t supported
- password_changed()[source]¶
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()[source]¶
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()[source]¶
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 thekbdint_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, instructions, lang, prompts)[source]¶
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 returnNone
to move on to another authentication method.- Parameters
name (
str
) – The name of the challengeinstructions (
str
) – Instructions to the user about how to respond to the challengelang (
str
) – The language the challenge is inprompts (
list
of tuples ofstr
andbool
) – 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[source]¶
SSH server protocol handler
Applications may subclass this when implementing an SSH server to provide custom authentication and request handlers.
The method
begin_auth()
can be overridden decide whether or not authentication is required, and additional callbacks are provided for each form of authentication in cases where authentication information is not provided in the call tocreate_server()
.In addition, the methods
session_requested()
,connection_requested()
,server_requested()
,unix_connection_requested()
, orunix_server_requested()
can be overridden to handle requests to open sessions or direct connections or set up listeners for forwarded connections.Note
The authentication callbacks described here can be defined as coroutines. However, they may be cancelled if they are running when the SSH connection is closed by the client. If they attempt to catch the CancelledError exception to perform cleanup, they should make sure to re-raise it to allow AsyncSSH to finish its own cleanup.
General connection handlers
- connection_made(conn)[source]¶
Called when a connection is made
This method is called when a new TCP connection is accepted. The
conn
parameter should be stored if needed for later use.- Parameters
conn (
SSHServerConnection
) – The connection which was successfully opened
General authentication handlers
- begin_auth(username)[source]¶
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 returnTrue
to indicate that authentication should proceed.If blocking operations need to be performed to prepare the state needed to complete the authentication, this method may be defined as a coroutine.
- auth_completed()[source]¶
Authentication was completed successfully
This method is called when authentication has completed successfully. Applications may use this method to perform processing based on the authenticated username or options in the authorized keys list or certificate associated with the user before any sessions are opened or forwarding requests are handled.
GSSAPI authentication handlers
- validate_gss_principal(username, user_principal, host_principal)[source]¶
Return whether a GSS principal is valid for this user
This method should return
True
if the specified user principal is valid for the user being authenticated. It can be overridden by applications wishing to perform their own authentication.If blocking operations need to be performed to determine the validity of the principal, this method may be defined as a coroutine.
By default, this method will return
True
only when the name in the user principal exactly matches the username and the domain of the user principal matches the domain of the host principal.
Host-based authentication handlers
- host_based_auth_supported()[source]¶
Return whether or not host-based authentication is supported
This method should return
True
if client host-based authentication is supported. Applications wishing to support it must have this method returnTrue
and implementvalidate_host_public_key()
and/orvalidate_host_ca_key()
to return whether or not the key provided by the client is valid for the client host being authenticated.By default, it returns
False
indicating the client host based authentication is not supported.- Returns
A
bool
indicating if host-based authentication is supported or not
- validate_host_public_key(client_host, client_addr, client_port, key)[source]¶
Return whether key is an authorized host key for this client host
Host key based client authentication can be supported by passing authorized host keys in the
known_client_hosts
argument ofcreate_server()
. 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 returnTrue
if the specified key is a valid host key for the client host 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.By default, this method returns
False
for all client host keys.Note
This function only needs to report whether the public key provided is a valid key for this client host. If it is, AsyncSSH will verify that the client possesses the corresponding private key before allowing the authentication to succeed.
- Parameters
- Returns
A
bool
indicating if the specified key is a valid key for the client host being authenticated
- validate_host_ca_key(client_host, client_addr, client_port, key)[source]¶
Return whether key is an authorized CA key for this client host
Certificate based client host authentication can be supported by passing authorized host CA keys in the
known_client_hosts
argument ofcreate_server()
. 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 returnTrue
if the specified key is a valid certificate authority key for the client host 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.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 client host. If it is, AsyncSSH will verify that the certificate is valid, that the client host 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
- Returns
A
bool
indicating if the specified key is a valid CA key for the client host being authenticated
- validate_host_based_user(username, client_host, client_username)[source]¶
Return whether remote host and user is authorized for this user
This method should return
True
if the specified client host and user is valid for the user being authenticated. It can be overridden by applications wishing to enforce restrictions on which remote users are allowed to authenticate as particular local users.If blocking operations need to be performed to determine the validity of the client host and user, this method may be defined as a coroutine.
By default, this method will return
True
when the client username matches the name of the user being authenticated.- Parameters
- Returns
A
bool
indicating if the specified client host and user is valid for the user being authenticated
Public key authentication handlers
- public_key_auth_supported()[source]¶
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 returnTrue
and implementvalidate_public_key()
and/orvalidate_ca_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
bool
indicating if public key authentication is supported or not
- validate_public_key(username, key)[source]¶
Return whether key is an authorized client key for this user
Key based client authentication can be supported by passing authorized keys in the
authorized_client_keys
argument ofcreate_server()
, or by callingset_authorized_keys
on the server connection from thebegin_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 returnTrue
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.
- validate_ca_key(username, key)[source]¶
Return whether key is an authorized CA key for this user
Certificate based client authentication can be supported by passing authorized CA keys in the
authorized_client_keys
argument ofcreate_server()
, or by callingset_authorized_keys
on the server connection from thebegin_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 returnTrue
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.
Password authentication handlers
- password_auth_supported()[source]¶
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 returnTrue
and implementvalidate_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
bool
indicating if password authentication is supported or not
- validate_password(username, password)[source]¶
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.If the password provided is valid but expired, this method may raise
PasswordChangeRequired
to request that the client provide a new password before authentication is allowed to complete. In this case, the application must overridechange_password()
to handle the password change request.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 returningFalse
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
- Returns
A
bool
indicating if the specified password is valid for the user being authenticated- Raises
PasswordChangeRequired
if the password provided is expired and needs to be changed
- change_password(username, old_password, new_password)[source]¶
Handle a request to change a user’s password
This method is called when a user makes a request to change their password. It should first validate that the old password provided is correct and then attempt to change the user’s password to the new value.
If the old password provided is valid and the change to the new password is successful, this method should return
True
. If the old password is not valid or password changes are not supported, it should returnFalse
. It may also raisePasswordChangeRequired
to request that the client try again if the new password is not acceptable for some reason.If blocking operations need to be performed to determine the validity of the old password or to change to the new password, this method may be defined as a coroutine.
By default, this method returns
False
, rejecting all password changes.- Parameters
- Returns
A
bool
indicating if the password change is successful or not- Raises
PasswordChangeRequired
if the new password is not acceptable and the client should be asked to provide another
Keyboard-interactive authentication handlers
- kbdint_auth_supported()[source]¶
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 returnTrue
and implementget_kbdint_challenge()
andvalidate_kbdint_response()
to generate the appropriate challenges and validate the responses for the user being authenticated.By default, this method returns
NotImplemented
tying this authentication to password authentication. If the application implements password authentication and this method is not overridden, keyboard-interactive authentication will be supported by prompting for a password and passing that to the password authentication callbacks.- Returns
A
bool
indicating if keyboard-interactive authentication is supported or not
- get_kbdint_challenge(username, lang, submethods)[source]¶
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
- Returns
An authentication challenge as described above
- validate_kbdint_response(username, responses)[source]¶
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 byget_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.
Channel session open handlers
- session_requested()[source]¶
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 anSSHServerChannel
object created withcreate_server_channel
and anSSHServerSession
, 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 itself. This can be either returned directly or as a part of a tuple with anSSHServerChannel
object.To reject this request, this method should return
False
to send back a “Session refused” response or raise aChannelOpenError
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 anSSHServerSession
A tuple consisting of an
SSHServerChannel
and the aboveA
callable
or coroutine handler function which takes AsyncSSH stream objects for stdin, stdout, and stderr as argumentsA tuple consisting of an
SSHServerChannel
and the aboveFalse
to refuse the request
- Raises
ChannelOpenError
if the session shouldn’t be accepted
- connection_requested(dest_host, dest_port, orig_host, orig_port)[source]¶
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 anChannelOpenError
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 anSSHTCPChannel
object created withcreate_tcp_channel()
and anSSHTCPSession
, 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 itself. This can be either returned directly or as a part of a tuple with anSSHTCPChannel
object.By default, all connection requests are rejected.
- Parameters
- Returns
One of the following:
An
SSHTCPSession
object or a coroutine which returns anSSHTCPSession
A tuple consisting of an
SSHTCPChannel
and the aboveA
callable
or coroutine handler function which takes AsyncSSH stream objects for reading from and writing to the connectionA tuple consisting of an
SSHTCPChannel
and the aboveTrue
to request standard port forwardingFalse
to refuse the connection
- Raises
ChannelOpenError
if the connection shouldn’t be accepted
- unix_connection_requested(dest_path)[source]¶
Handle a direct UNIX domain socket connection request
This method is called when a direct UNIX domain socket connection request is received by the server. Applications wishing to accept such connections must override this method.
To allow standard path forwarding of data on the connection to the requested destination path, this method should return
True
.To reject this request, this method should return
False
to send back a “Connection refused” response or raise anChannelOpenError
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
SSHUNIXSession
object which can be used to process the data received on the channel or a tuple consisting of of anSSHUNIXChannel
object created withcreate_unix_channel()
and anSSHUNIXSession
, 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
SSHUNIXSession
object can be returned instead of the session itself. This can be either returned directly or as a part of a tuple with anSSHUNIXChannel
object.By default, all connection requests are rejected.
- Parameters
dest_path (
str
) – The path the client wishes to connect to- Returns
One of the following:
An
SSHUNIXSession
object or a coroutine which returns anSSHUNIXSession
A tuple consisting of an
SSHUNIXChannel
and the aboveA
callable
or coroutine handler function which takes AsyncSSH stream objects for reading from and writing to the connectionA tuple consisting of an
SSHUNIXChannel
and the aboveTrue
to request standard path forwardingFalse
to refuse the connection
- Raises
ChannelOpenError
if the connection shouldn’t be accepted
- server_requested(listen_host, listen_port)[source]¶
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 callscreate_connection
on each of them to forward them back to the client or returnNone
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
- Returns
One of the following:
An
SSHListener
objectTrue
to set up standard port forwardingFalse
to reject the requestA coroutine object which returns one of the above
- unix_server_requested(listen_path)[source]¶
Handle a request to listen on a UNIX domain socket
This method is called when a client makes a request to listen on a path for incoming UNIX domain socket connections. Applications wishing to allow UNIX domain socket forwarding must override this method.
To set up standard path forwarding of connections received on this path, 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 callscreate_unix_connection
on each of them to forward them back to the client or returnNone
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_path (
str
) – The path the server should listen on- Returns
One of the following:
An
SSHListener
object or a coroutine which returns anSSHListener
orFalse
if the listener can’t be openedTrue
to set up standard path forwardingFalse
to reject the request
Connection Classes¶
SSHClientConnection¶
- class asyncssh.SSHClientConnection[source]¶
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()
.Direct UNIX domain socket connections can be opened by calling
create_unix_connection()
.Remote listeners for forwarded UNIX domain socket connections can be opened by calling
create_unix_server()
.TCP port forwarding can be set up by calling
forward_local_port()
orforward_remote_port()
.UNIX domain socket forwarding can be set up by calling
forward_local_path()
orforward_remote_path()
.Mixed forwarding from a TCP port to a UNIX domain socket or vice-versa can be set up by calling
forward_local_port_to_path()
,forward_local_path_to_port()
,forward_remote_port_to_path()
, orforward_remote_path_to_port()
.Connection attributes
- logger¶
A logger associated with this connection
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:
usernameclient_versionserver_versionsend_ciphersend_macsend_compressionrecv_cipherrecv_macrecv_compressionSee
get_extra_info()
inasyncio.BaseTransport
for more information.Additional information stored on the connection by calling
set_extra_info()
can also be returned here.
- set_extra_info(**kwargs)¶
Store additional information associated with the connection
This method allows extra information to be associated with the connection. The information to store should be passed in as keyword parameters and can later be returned by calling
get_extra_info()
with one of the keywords as the name to retrieve.
- set_keepalive(interval=None, count_max=None)¶
Set keep-alive timer on this connection
This method sets the parameters of the keepalive timer on the connection. If interval is set to a non-zero value, keep-alive requests will be sent whenever the connection is idle, and if a response is not received after count_max attempts, the connection is closed.
- Parameters
interval (
int
,float
, orstr
) – (optional) The time in seconds to wait before sending a keep-alive message if no data has been received. This defaults to 0, which disables sending these messages.count_max (
int
) – (optional) The maximum number of keepalive messages which will be sent without getting a response before closing the connection. This defaults to 3, but only applies when interval is non-zero.
- 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.
Client session open methods
- async create_session(session_factory, command=(), *, subsystem=(), env=(), send_env=(), request_pty=(), term_type=(), term_size=(), term_modes=(), x11_forwarding=(), x11_display=(), x11_auth_path=(), x11_single_connection=(), encoding=(), errors=(), window=(), max_pktsize=())[source]¶
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 specified 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. When an encoding is set, an optional errors argument can be passed in to select what Unicode error handling strategy to use.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
) – Acallable
which returns anSSHClientSession
object that will be created to handle activity on this sessioncommand (
str
) – (optional) The remote command to execute. By default, an interactive shell is started if no command or subsystem is provided.subsystem (
str
) – (optional) The name of a remote subsystem to start up.env (
dict
withstr
keys and values) –(optional) The 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.
send_env (
list
ofstr
) – (optional) A list of environment variable names to pull fromos.environ
and set for this session. Wildcards patterns using'*'
and'?'
are allowed, and all variables with matching names will be sent with whatever value is set in the local environment. If a variable is present in both env and send_env, the value from env will be used.request_pty (
bool
,'force'
, or'auto'
) – (optional) Whether or not to request a pseudo-terminal (PTY) for this session. This defaults toTrue
, which means to request a PTY whenever theterm_type
is set. Other possible values includeFalse
to never request a PTY,'force'
to always request a PTY even withoutterm_type
being set, or'auto'
to request a TTY whenterm_type
is set but only when starting an interactive shell.term_type (
str
) – (optional) The terminal type to set for this session.term_size (
tuple
of 2 or 4int
values) – (optional) The terminal width and height in characters and optionally the width and height in pixels.term_modes (
dict
withint
keys and values) – (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.x11_forwarding (
bool
or'ignore_failure'
) – (optional) Whether or not to request X11 forwarding for this session, defaulting toFalse
. If set toTrue
, X11 forwarding will be requested and a failure will raiseChannelOpenError
. It can also be set to'ignore_failure'
to attempt X11 forwarding but ignore failures.x11_display (
str
) – (optional) The display that X11 connections should be forwarded to, defaulting to the value in the environment variableDISPLAY
.x11_auth_path (
str
) – (optional) The path to the Xauthority file to read X11 authentication data from, defaulting to the value in the environment variableXAUTHORITY
or the file.Xauthority
in the user’s home directory if that’s not set.x11_single_connection (
bool
) – (optional) Whether or not to limit X11 forwarding to a single connection, defaulting toFalse
.encoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on this session.errors (
str
) – (optional) The error handling strategy to apply on Unicode encode/decode errors.window (
int
) – (optional) The receive window size for this session.max_pktsize (
int
) – (optional) The maximum packet size for this session.
- Returns
an
SSHClientChannel
andSSHClientSession
- Raises
ChannelOpenError
if the session can’t be opened
- async open_session(*args, **kwargs)[source]¶
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 asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it returns anSSHWriter
and twoSSHReader
objects representing stdin, stdout, and stderr which can be used to perform I/O on the session. With the exception ofsession_factory
, all of the arguments tocreate_session()
are supported and have the same meaning.
- create_process(*args, bufsize=io.DEFAULT_BUFFER_SIZE, input=None, stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)[source]¶
Create a process on the remote system
This method is a coroutine wrapper around
create_session()
which can be used to execute a command, start a subsystem, or start an interactive shell, optionally redirecting stdin, stdout, and stderr to and from files or pipes attached to other local and remote processes.By default, the stdin, stdout, and stderr arguments default to the special value
PIPE
which means that they can be read and written interactively via stream objects which are members of theSSHClientProcess
object this method returns. If other file-like objects are provided as arguments, input or output will automatically be redirected to them. The special valueDEVNULL
can be used to provide no input or discard all output, and the special valueSTDOUT
can be provided asstderr
to send its output to the same stream asstdout
.In addition to the arguments below, all arguments to
create_session()
except forsession_factory
are supported and have the same meaning.- Parameters
input (
str
orbytes
) – (optional) Input data to feed to standard input of the remote process. If specified, this argument takes precedence over stdin. Data should be astr
if encoding is set, orbytes
if not.stdin – (optional) A filename, file-like object, file descriptor, socket, or
SSHReader
to feed to standard input of the remote process, orDEVNULL
to provide no input.stdout – (optional) A filename, file-like object, file descriptor, socket, or
SSHWriter
to feed standard output of the remote process to, orDEVNULL
to discard this output.stderr – (optional) A filename, file-like object, file descriptor, socket, or
SSHWriter
to feed standard error of the remote process to,DEVNULL
to discard this output, orSTDOUT
to feed standard error to the same place as stdout.bufsize (
int
) – (optional) Buffer size to use when feeding data from a file to stdinsend_eof (
bool
) – Whether or not to send EOF to the channel when EOF is received from stdin, defaulting toTrue
. If set toFalse
, the channel will remain open after EOF is received on stdin, and multiple sources can be redirected to the channel.recv_eof (
bool
) – Whether or not to send EOF to stdout and stderr when EOF is received from the channel, defaulting toTrue
. If set toFalse
, the redirect targets of stdout and stderr will remain open after EOF is received on the channel and can be used for multiple redirects.
- Returns
- Raises
ChannelOpenError
if the channel can’t be opened
- async create_subprocess(protocol_factory, *args, bufsize=io.DEFAULT_BUFFER_SIZE, input=None, stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)[source]¶
Create a subprocess on the remote system
This method is a coroutine wrapper around
create_session()
which can be used to execute a command, start a subsystem, or start an interactive shell, optionally redirecting stdin, stdout, and stderr to and from files or pipes attached to other local and remote processes similar tocreate_process()
. However, instead of performing interactive I/O usingSSHReader
andSSHWriter
objects, the caller provides a function which returns an object which conforms to theasyncio.SubprocessProtocol
and this call returns that and anSSHSubprocessTransport
object which conforms toasyncio.SubprocessTransport
.With the exception of the addition of
protocol_factory
, all of the arguments are the same ascreate_process()
.- Parameters
protocol_factory (
callable
) – Acallable
which returns anSSHSubprocessProtocol
object that will be created to handle activity on this session.- Returns
- Raises
ChannelOpenError
if the channel can’t be opened
- async run(*args, check=False, timeout=None, **kwargs)[source]¶
Run a command on the remote system and collect its output
This method is a coroutine wrapper around
create_process()
which can be used to run a process to completion when no interactivity is needed. All of the arguments tocreate_process()
can be passed in to provide input or redirect stdin, stdout, and stderr, but this method waits until the process exits and returns anSSHCompletedProcess
object with the exit status or signal information and the output to stdout and stderr (if not redirected).If the check argument is set to
True
, a non-zero exit status from the remote process will trigger theProcessError
exception to be raised.In addition to the argument below, all arguments to
create_process()
are supported and have the same meaning.If a timeout is specified and it expires before the process exits, the
TimeoutError
exception will be raised. By default, no timeout is set and this call will wait indefinitely.- Parameters
- Returns
- Raises
ChannelOpenError
if the session can’t be openedProcessError
if checking non-zero exit statusTimeoutError
if the timeout expires before exit
- start_sftp_client(env=(), send_env=(), path_encoding='utf-8', path_errors='strict', sftp_version=3)[source]¶
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
env (
dict
withstr
keys and values) –(optional) The environment variables to set for this SFTP 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.
send_env (
list
ofstr
) – (optional) A list of environment variable names to pull fromos.environ
and set for this SFTP session. Wildcards patterns using'*'
and'?'
are allowed, and all variables with matching names will be sent with whatever value is set in the local environment. If a variable is present in both env and send_env, the value from env will be used.path_encoding (
str
orNone
) – The Unicode encoding to apply when sending and receiving remote pathnamespath_errors (
str
) – The error handling strategy to apply on encode/decode errorssftp_version (
int
) – (optional) The maximum version of the SFTP protocol to support, currently either 3 or 4, defaulting to 3.
- Returns
- Raises
SFTPError
if the session can’t be opened
- async create_ssh_connection(client_factory, host, port=(), **kwargs)[source]¶
Create a tunneled SSH client connection
This method is a coroutine which can be called to open an SSH client connection to the requested host and port tunneled inside this already established connection. It takes all the same arguments as
create_connection()
but requests that the upstream SSH server open the connection rather than connecting directly.
- connect_ssh(host, port=(), **kwargs)[source]¶
Make a tunneled SSH client connection
This method is a coroutine which can be called to open an SSH client connection to the requested host and port tunneled inside this already established connection. It takes all the same arguments as
connect()
but requests that the upstream SSH server open the connection rather than connecting directly.
- connect_reverse_ssh(host, port=(), **kwargs)[source]¶
Make a tunneled reverse direction SSH connection
This method is a coroutine which can be called to open an SSH client connection to the requested host and port tunneled inside this already established connection. It takes all the same arguments as
connect()
but requests that the upstream SSH server open the connection rather than connecting directly.
- listen_ssh(host='', port=(), **kwargs)[source]¶
Create a tunneled SSH listener
This method is a coroutine which can be called to open a remote SSH listener on the requested host and port tunneled inside this already established connection. It takes all the same arguments as
listen()
but requests that the upstream SSH server open the listener rather than listening directly via TCP/IP.
- listen_reverse_ssh(host='', port=(), **kwargs)[source]¶
Create a tunneled reverse direction SSH listener
This method is a coroutine which can be called to open a remote SSH listener on the requested host and port tunneled inside this already established connection. It takes all the same arguments as
listen_reverse()
but requests that the upstream SSH server open the listener rather than listening directly via TCP/IP.
Client connection open methods
- async create_connection(session_factory, remote_host, remote_port, orig_host='', orig_port=0, *, encoding=None, errors='strict', window=2097152, max_pktsize=32768)[source]¶
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 bysession_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. When encoding is set, an optional errors argument can be passed in to select what Unicode error handling strategy to use.
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
) – Acallable
which returns anSSHTCPSession
object that will be created to handle activity on this sessionremote_host (
str
) – The remote hostname or address to connect toremote_port (
int
) – The remote port number to connect toorig_host (
str
) – (optional) The hostname or address of the client requesting the connectionorig_port (
int
) – (optional) The port number of the client requesting the connectionencoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connectionerrors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
an
SSHTCPChannel
andSSHTCPSession
- Raises
ChannelOpenError
if the connection can’t be opened
- async open_connection(*args, **kwargs)[source]¶
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 asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it returnsSSHReader
andSSHWriter
objects which can be used to perform I/O on the connection.With the exception of
session_factory
, all of the arguments tocreate_connection()
are supported and have the same meaning here.- Returns
- Raises
ChannelOpenError
if the connection can’t be opened
- create_server(session_factory, listen_host, listen_port, *, encoding=None, errors='strict', window=2097152, max_pktsize=32768)[source]¶
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) – Acallable
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 anSSHTCPSession
object used to handle activity on that connection or raisingChannelOpenError
to indicate that the connection should not be acceptedlisten_host (
str
) – The hostname or address on the remote host to listen onlisten_port (
int
) – The port number on the remote host to listen onencoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connectionerrors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- start_server(handler_factory, *args, **kwargs)[source]¶
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 asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it takes ahandler_factory
which returns acallable
or coroutine that will be passedSSHReader
andSSHWriter
objects which can be used to perform I/O on each new connection which arrives. Likecreate_server()
,handler_factory
can also raiseChannelOpenError
if the connection should not be accepted.With the exception of
handler_factory
replacingsession_factory
, all of the arguments tocreate_server()
are supported and have the same meaning here.- Parameters
handler_factory (
callable
or coroutine) – Acallable
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 raisingChannelOpenError
to indicate that the connection should not be accepted- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- async create_unix_connection(session_factory, remote_path, *, encoding=None, errors='strict', window=2097152, max_pktsize=32768)[source]¶
Create an SSH UNIX domain socket direct connection
This method is a coroutine which can be called to request that the server open a new outbound UNIX domain socket connection to the specified destination path. If the connection is successfully opened, a new SSH channel will be opened with data being handled by a
SSHUNIXSession
object created bysession_factory
.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 to send and receive string data. When encoding is set, an optional errors argument can be passed in to select what Unicode error handling strategy to use.
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
) – Acallable
which returns anSSHUNIXSession
object that will be created to handle activity on this sessionremote_path (
str
) – The remote path to connect toencoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connectionerrors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
an
SSHUNIXChannel
andSSHUNIXSession
- Raises
ChannelOpenError
if the connection can’t be opened
- async open_unix_connection(*args, **kwargs)[source]¶
Open an SSH UNIX domain socket direct connection
This method is a coroutine wrapper around
create_unix_connection()
designed to provide a “high-level” stream interface for creating an SSH UNIX domain socket direct connection. Instead of taking asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it returnsSSHReader
andSSHWriter
objects which can be used to perform I/O on the connection.With the exception of
session_factory
, all of the arguments tocreate_unix_connection()
are supported and have the same meaning here.- Returns
- Raises
ChannelOpenError
if the connection can’t be opened
- create_unix_server(session_factory, listen_path, *, encoding=None, errors='strict', window=2097152, max_pktsize=32768)[source]¶
Create a remote SSH UNIX domain socket listener
This method is a coroutine which can be called to request that the server listen on the specified remote path for incoming UNIX domain socket 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
) – Acallable
or coroutine which decides whether to accept the connection or not, either returning anSSHUNIXSession
object used to handle activity on that connection or raisingChannelOpenError
to indicate that the connection should not be acceptedlisten_path (
str
) – The path on the remote host to listen onencoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connectionerrors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- start_unix_server(handler_factory, *args, **kwargs)[source]¶
Start a remote SSH UNIX domain socket listener
This method is a coroutine wrapper around
create_unix_server()
designed to provide a “high-level” stream interface for creating remote SSH UNIX domain socket listeners. Instead of taking asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it takes ahandler_factory
which returns acallable
or coroutine that will be passedSSHReader
andSSHWriter
objects which can be used to perform I/O on each new connection which arrives. Likecreate_unix_server()
,handler_factory
can also raiseChannelOpenError
if the connection should not be accepted.With the exception of
handler_factory
replacingsession_factory
, all of the arguments tocreate_unix_server()
are supported and have the same meaning here.- Parameters
handler_factory (
callable
or coroutine) – Acallable
or coroutine which decides whether to accept the UNIX domain socket connection or not, either returning a callback or coroutine used to handle activity on that connection or raisingChannelOpenError
to indicate that the connection should not be accepted- Returns
- Raises
ChannelListenError
if the listener can’t be opened
Client forwarding methods
- async forward_connection(dest_host, dest_port)¶
Forward a tunneled TCP 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
- Returns
- forward_local_port(listen_host, listen_port, dest_host, dest_port, accept_handler=None)¶
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 (
str
) – The hostname or address on the local host to listen onlisten_port (
int
) – The port number on the local host to listen ondest_host (
str
) – The hostname or address to forward the connections todest_port (
int
) – The port number to forward the connections toaccept_handler (
callable
or coroutine) – Acallable
or coroutine which takes arguments of the original host and port of the client and decides whether or not to allow connection forwarding, returningTrue
to accept the connection and begin forwarding orFalse
to reject and close it.
- Returns
- Raises
OSError
if the listener can’t be opened
- forward_local_path(listen_path, dest_path)¶
Set up local UNIX domain socket forwarding
This method is a coroutine which attempts to set up UNIX domain socket forwarding from a local listening path to a remote path 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 UNIX domain socket forwarding.- Parameters
- Returns
- Raises
OSError
if the listener can’t be opened
- forward_local_port_to_path(listen_host, listen_port, dest_path, accept_handler=None)[source]¶
Set up local TCP port forwarding to a remote UNIX domain socket
This method is a coroutine which attempts to set up port forwarding from a local TCP listening port to a remote UNIX domain path 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 (
str
) – The hostname or address on the local host to listen onlisten_port (
int
) – The port number on the local host to listen ondest_path (
str
) – The path on the remote host to forward the connections toaccept_handler (
callable
or coroutine) – Acallable
or coroutine which takes arguments of the original host and port of the client and decides whether or not to allow connection forwarding, returningTrue
to accept the connection and begin forwarding orFalse
to reject and close it.
- Returns
- Raises
OSError
if the listener can’t be opened
- forward_local_path_to_port(listen_path, dest_host, dest_port)[source]¶
Set up local UNIX domain socket forwarding to a remote TCP port
This method is a coroutine which attempts to set up UNIX domain socket forwarding from a local listening path 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 UNIX domain socket forwarding.- Parameters
- Returns
- Raises
OSError
if the listener can’t be opened
- forward_remote_port(listen_host, listen_port, dest_host, dest_port)[source]¶
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
- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- forward_remote_path(listen_path, dest_path)[source]¶
Set up remote UNIX domain socket forwarding
This method is a coroutine which attempts to set up UNIX domain socket forwarding from a remote listening path to a local path 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
- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- forward_remote_port_to_path(listen_host, listen_port, dest_path)[source]¶
Set up remote TCP port forwarding to a local UNIX domain socket
This method is a coroutine which attempts to set up port forwarding from a remote TCP listening port to a local UNIX domain socket path 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
- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- forward_remote_path_to_port(listen_path, dest_host, dest_port)[source]¶
Set up remote UNIX domain socket forwarding to a local TCP port
This method is a coroutine which attempts to set up UNIX domain socket forwarding from a remote listening path to a local TCP 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
- Returns
- Raises
ChannelListenError
if the listener can’t be opened
- forward_socks(listen_host, listen_port)[source]¶
Set up local port forwarding via SOCKS
This method is a coroutine which attempts to set up dynamic port forwarding via SOCKS on the specified local host and port. Each SOCKS request contains the destination host and port to connect to and triggers a request to tunnel traffic to the requested 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
- Returns
- Raises
OSError
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 without 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 associatedSSHClient
object will be called with the valueNone
.
- 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 associatedSSHClient
orSSHServer
object will be called with the valueNone
.- Parameters
code (
int
) – The reason for the disconnect, from disconnect reason codesreason (
str
) – A human readable reason for the disconnectlang (
str
) – The language the reason is in
- async wait_closed()¶
Wait for this connection to close
This method is a coroutine which can be called to block until this connection has finished closing.
SSHServerConnection¶
- class asyncssh.SSHServerConnection[source]¶
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 callcreate_server_channel()
from theirsession_requested()
method and return a tuple of theSSHServerChannel
object returned from that and either anSSHServerSession
object or a coroutine which returns anSSHServerSession
.Similarly,
SSHServer
objects wishing to create TCP connection objects with non-default channel properties can callcreate_tcp_channel()
from theirconnection_requested()
method and return a tuple of theSSHTCPChannel
object returned from that and either anSSHTCPSession
object or a coroutine which returns anSSHTCPSession
.SSHServer
objects wishing to create UNIX domain socket connection objects with non-default channel properties can callcreate_unix_channel()
from theunix_connection_requested()
method and return a tuple of theSSHUNIXChannel
object returned from that and either anSSHUNIXSession
object or a coroutine which returns anSSHUNIXSession
.Connection attributes
- logger¶
A logger associated with this connection
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:
usernameclient_versionserver_versionsend_ciphersend_macsend_compressionrecv_cipherrecv_macrecv_compressionSee
get_extra_info()
inasyncio.BaseTransport
for more information.Additional information stored on the connection by calling
set_extra_info()
can also be returned here.
- set_extra_info(**kwargs)¶
Store additional information associated with the connection
This method allows extra information to be associated with the connection. The information to store should be passed in as keyword parameters and can later be returned by calling
get_extra_info()
with one of the keywords as the name to retrieve.
- set_keepalive(interval=None, count_max=None)¶
Set keep-alive timer on this connection
This method sets the parameters of the keepalive timer on the connection. If interval is set to a non-zero value, keep-alive requests will be sent whenever the connection is idle, and if a response is not received after count_max attempts, the connection is closed.
- Parameters
interval (
int
,float
, orstr
) – (optional) The time in seconds to wait before sending a keep-alive message if no data has been received. This defaults to 0, which disables sending these messages.count_max (
int
) – (optional) The maximum number of keepalive messages which will be sent without getting a response before closing the connection. This defaults to 3, but only applies when interval is non-zero.
- 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.
Server authentication methods
- set_authorized_keys(authorized_keys)[source]¶
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 ofSSHServer
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)[source]¶
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)no-touch-required (boolean)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 (
str
) – 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)[source]¶
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-forwardingagent-forwardingport-forwardingptyuser-rcAsyncSSH internally enforces X11-forwarding, agent-forwarding, port-forwarding and pty permissions but ignores user-rc since it does not implement that feature.
Non-standard permissions can also be checked, as long as the option follows the convention of starting with ‘no-‘.
- get_certificate_option(option, default=None)[source]¶
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)no-touch-required (boolean)source-address (list of CIDR-style IP network addresses)- Parameters
option (
str
) – 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)[source]¶
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-forwardingagent-forwardingport-forwardingptyuser-rcAsyncSSH internally enforces agent-forwarding, port-forwarding and pty permissions but ignores the other values since it does not implement those features.
Server connection open methods
- async create_connection(session_factory, remote_host, remote_port, orig_host='', orig_port=0, *, encoding=None, errors='strict', window=2097152, max_pktsize=32768)[source]¶
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 remote 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 bysession_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 to send and receive string data. When encoding is set, an optional errors argument can be passed in to select what Unicode error handling strategy to use.
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
) – Acallable
which returns anSSHTCPSession
object that will be created to handle activity on this sessionremote_host (
str
) – The hostname or address the connection was received onremote_port (
int
) – The port number the connection was received onorig_host (
str
) – (optional) The hostname or address of the client requesting the connectionorig_port (
int
) – (optional) The port number of the client requesting the connectionencoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connectionerrors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
an
SSHTCPChannel
andSSHTCPSession
- async open_connection(*args, **kwargs)[source]¶
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 asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it returnsSSHReader
andSSHWriter
objects which can be used to perform I/O on the connection.With the exception of
session_factory
, all of the arguments tocreate_connection()
are supported and have the same meaning here.
- async create_unix_connection(session_factory, remote_path, *, encoding=None, errors='strict', window=2097152, max_pktsize=32768)[source]¶
Create an SSH UNIX domain socket forwarded connection
This method is a coroutine which can be called to notify the client about a new inbound UNIX domain socket connection arriving on the specified remote path. If the connection is successfully opened, a new SSH channel will be opened with data being handled by a
SSHUNIXSession
object created bysession_factory
.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 to send and receive string data. When encoding is set, an optional errors argument can be passed in to select what Unicode error handling strategy to use.
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
) – Acallable
which returns anSSHUNIXSession
object that will be created to handle activity on this sessionremote_path (
str
) – The path the connection was received onencoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connectionerrors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
an
SSHTCPChannel
andSSHUNIXSession
- async open_unix_connection(*args, **kwargs)[source]¶
Open an SSH UNIX domain socket forwarded connection
This method is a coroutine wrapper around
create_unix_connection()
designed to provide a “high-level” stream interface for creating an SSH UNIX domain socket forwarded connection. Instead of taking asession_factory
argument for constructing an object which will handle activity on the session via callbacks, it returnsSSHReader
andSSHWriter
objects which can be used to perform I/O on the connection.With the exception of
session_factory
, all of the arguments tocreate_unix_connection()
are supported and have the same meaning here.
Server forwarding methods
- async forward_connection(dest_host, dest_port)¶
Forward a tunneled TCP 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
- Returns
- async forward_unix_connection(dest_path)¶
Forward a tunneled UNIX domain socket connection
This method is a coroutine which can be returned by a
session_factory
to forward connections tunneled over SSH to the specified destination path.- Parameters
dest_path (
str
) – The path to forward the connection to- Returns
Server channel creation methods
- create_server_channel(encoding='', errors='', window=0, max_pktsize=0)[source]¶
Create an SSH server channel for a new SSH session
This method can be called by
session_requested()
to create anSSHServerChannel
with the desired encoding, Unicode error handling strategy, window, and max packet size for a newly created SSH server session.- Parameters
encoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the session, defaulting to UTF-8 (ISO 10646) format. IfNone
is passed in, the application can send and receive raw bytes.errors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
- create_tcp_channel(encoding=None, errors='strict', 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 anSSHTCPChannel
with the desired encoding, Unicode error handling strategy, window, and max packet size for a newly created SSH direct connection.- Parameters
encoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connection. This defaults toNone
, allowing the application to send and receive raw bytes.errors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
- create_unix_channel(encoding=None, errors='strict', window=2097152, max_pktsize=32768)¶
Create an SSH UNIX channel for a new direct UNIX domain connection
This method can be called by
unix_connection_requested()
to create anSSHUNIXChannel
with the desired encoding, Unicode error handling strategy, window, and max packet size for a newly created SSH direct UNIX domain socket connection.- Parameters
encoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on the connection. This defaults toNone
, allowing the application to send and receive raw bytes.errors (
str
) – (optional) The error handling strategy to apply on encode/decode errorswindow (
int
) – (optional) The receive window size for this sessionmax_pktsize (
int
) – (optional) The maximum packet size for this session
- Returns
Connection close methods
- abort()¶
Forcibly close the SSH connection
This method closes the SSH connection immediately, without waiting for pending operations to complete and without 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 associatedSSHClient
object will be called with the valueNone
.
- 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 associatedSSHClient
orSSHServer
object will be called with the valueNone
.- Parameters
code (
int
) – The reason for the disconnect, from disconnect reason codesreason (
str
) – A human readable reason for the disconnectlang (
str
) – The language the reason is in
- async wait_closed()¶
Wait for this connection to close
This method is a coroutine which can be called to block until this connection has finished closing.
SSHClientConnectionOptions¶
- class asyncssh.SSHClientConnectionOptions[source]¶
SSH client connection options
The following options are available to control the establishment of SSH client connections:
- Parameters
client_factory (
callable
returningSSHClient
) – (optional) Acallable
which returns anSSHClient
object that will be created for each new connection.proxy_command (
str
orlist
ofstr
) – (optional) A string or list of strings specifying a command and arguments to run to make a connection to the SSH server. Data will be forwarded to this process over stdin/stdout instead of opening a TCP connection. If specified as a string, standard shell quoting will be applied when splitting the command and its arguments.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 toNone
, server host key validation will be disabled.host_key_alias (
str
) – (optional) An alias to use instead of the real host name when looking up a host key in known_hosts and when validating host certificates.server_host_key_algs (
str
orlist
ofstr
) –(optional) A list of server host key algorithms to use instead of the default of those present in known_hosts when performing the SSH handshake, taken from server host key algorithms. This is useful when using the validate_host_public_key callback to validate server host keys, since AsyncSSH can not determine which server host key algorithms are preferred. This argument can also be set to ‘default’ to specify that the client should always send its default list of supported algorithms to avoid leaking information about what algorithms are present for the server in known_hosts.
Note
The ‘default’ keyword should be used with caution, as it can result in a host key mismatch if the client trusts only a subset of the host keys the server might return.
x509_trusted_certs (see Specifying certificates) –
(optional) A list of certificates which should be trusted for X.509 server certificate authentication. If no trusted certificates are specified, an attempt will be made to load them from the file
.ssh/ca-bundle.crt
. If this argument is explicitly set toNone
, X.509 server certificate authentication will not be performed.Note
X.509 certificates to trust can also be provided through a known_hosts file if they are converted into OpenSSH format. This allows their trust to be limited to only specific host names.
x509_trusted_cert_paths (
list
ofstr
) – (optional) A list of path names to “hash directories” containing certificates which should be trusted for X.509 server certificate authentication. Each certificate should be in a separate file with a name of the form hash.number, where hash is the OpenSSL hash value of the certificate subject name and number is an integer counting up from zero if multiple certificates have the same hash. If no paths are specified, an attempt with be made to use the directory.ssh/crt
as a certificate hash directory.x509_purposes (see Specifying X.509 purposes) – (optional) A list of purposes allowed in the ExtendedKeyUsage of a certificate used for X.509 server certificate authentication, defulting to ‘secureShellServer’. If this argument is explicitly set to
None
, the server certificate’s ExtendedKeyUsage will not be checked.username (
str
) – (optional) Username to authenticate as on the server. If not specified, the currently logged in user on the local machine will be used.password (
str
) – (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.client_host_keysign (
bool
orstr
) – (optional) Whether or not to usessh-keysign
to sign host-based authentication requests. If set toTrue
, an attempt will be made to findssh-keysign
in its typical locations. If set to a string, that will be used as thessh-keysign
path. When set, client_host_keys should be a list of public keys. Otherwise, client_host_keys should be a list of private keys with optional paired certificates.client_host_keys (see Specifying private keys or Specifying public keys) – (optional) A list of keys to use to authenticate this client via host-based authentication. If
client_host_keysign
is set and no host keys or certificates are specified, an attempt will be made to find them in their typical locations. Ifclient_host_keysign
is not set, host private keys must be specified explicitly or host-based authentication will not be performed.client_host_certs (see Specifying certificates) – (optional) A list of optional certificates which can be paired with the provided client host keys.
client_host (
str
) – (optional) The local hostname to use when performing host-based authentication. If not specified, the hostname associated with the local IP address of the SSH connection will be used.client_username (
str
) – (optional) The local username to use when performing host-based authentication. If not specified, the username of the currently logged in user 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. These keys will be used after trying keys from a PKCS11 provider or an ssh-agent, if either of those are configured. If no client keys are specified, an attempt will be made to load them from the files
.ssh/id_ed25519_sk
,.ssh/id_ecdsa_sk
,.ssh/id_ed448
,.ssh/id_ed25519
,.ssh/id_ecdsa
,.ssh/id_rsa
, and.ssh/id_dsa
in the user’s home directory, with optional certificates loaded from the files.ssh/id_ed25519_sk-cert.pub
,.ssh/id_ecdsa_sk-cert.pub
,.ssh/id_ed448-cert.pub
,.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 toNone
, client public key authentication will not be performed.client_certs (see Specifying certificates) – (optional) A list of optional certificates which can be paired with the provided client keys.
passphrase (
str
orbytes
) – (optional) The passphrase to use to decrypt client keys when loading them, if they are encrypted. If this is not specified, only unencrypted client keys can be loaded. If the keys passed into client_keys are already loaded, this argument is ignored.ignore_encrypted (
bool
) – (optional) Whether or not to ignore encrypted keys when no passphrase is specified. This defaults toTrue
when keys are specified via the IdentityFile config option, causing encrypted keys in the config to be ignored when no passphrase is specified. Note that encrypted keys loaded into an SSH agent can still be used when this option is set.host_based_auth (
bool
) – (optional) Whether or not to allow host-based authentication. By default, host-based authentication is enabled if client host keys are made available.public_key_auth (
bool
) – (optional) Whether or not to allow public key authentication. By default, public key authentication is enabled if client keys are made available.kbdint_auth (
bool
) – (optional) Whether or not to allow keyboard-interactive authentication. By default, keyboard-interactive authentication is enabled if a password is specified or if callbacks to respond to challenges are made available.password_auth (
bool
) – (optional) Whether or not to allow password authentication. By default, password authentication is enabled if a password is specified or if callbacks to provide a password are made available.gss_host (
str
) – (optional) The principal name to use for the host in GSS key exchange and authentication. If not specified, this value will be the same as thehost
argument. If this argument is explicitly set toNone
, GSS key exchange and authentication will not be performed.gss_kex (
bool
) – (optional) Whether or not to allow GSS key exchange. By default, GSS key exchange is enabled.gss_auth (
bool
) – (optional) Whether or not to allow GSS authentication. By default, GSS authentication is enabled.gss_delegate_creds (
bool
) – (optional) Whether or not to forward GSS credentials to the server being accessed. By default, GSS credential delegation is disabled.preferred_auth (
str
orlist
ofstr
) – A list of authentication methods the client should attempt to use in order of preference. By default, the preferred list is gssapi-keyex, gssapi-with-mic, hostbased, publickey, keyboard-interactive, and then password. This list may be limited by which auth methods are implemented by the client and which methods the server accepts.disable_trivial_auth (
bool
) – (optional) Whether or not to allow “trivial” forms of auth where the client is not actually challenged for credentials. Setting this will cause the connection to fail if a server does not perform some non-trivial form of auth during the initial SSH handshake. If not specified, all forms of auth supported by the server are allowed, including none.agent_path (
str
) – (optional) The path of a UNIX domain socket to use to contact an ssh-agent process which will perform the operations needed for client public key authentication, or theSSHServerConnection
to use to forward ssh-agent requests over. If this is not specified and the environment variableSSH_AUTH_SOCK
is set, its value will be used as the path. If this argument is explicitly set toNone
, an ssh-agent will not be used.agent_identities (see Specifying public keys and Specifying certificates) – (optional) A list of identities used to restrict which SSH agent keys may be used. These may be specified as byte strings in binary SSH format or as public keys or certificates (see Specifying public keys and Specifying certificates). If set to
None
, all keys loaded into the SSH agent will be made available for use. This is the default.agent_forwarding (
bool
) – (optional) Whether or not to allow forwarding of ssh-agent requests from processes running on the server. By default, ssh-agent forwarding requests from the server are not allowed.pkcs11_provider (
str
) – (optional) The path of a shared library which should be used as a PKCS#11 provider for accessing keys on PIV security tokens. By default, no local security tokens will be accessed.pkcs11_pin (
str
) –(optional) The PIN to use when accessing security tokens via PKCS#11.
Note
If your application opens multiple SSH connections using PKCS#11 keys, you should consider calling
load_pkcs11_keys()
explicitly instead of using these arguments. This allows you to pay the cost of loading the key information from the security tokens only once. You can then pass the returned keys via theclient_keys
argument to any calls that need them.Calling
load_pkcs11_keys()
explicitly also gives you the ability to load keys from multiple tokens with different PINs and to select which tokens to load keys from and which keys on those tokens to load.client_version (
str
) – (optional) An ASCII string to advertise to the SSH server as the version of this client, defaulting to'AsyncSSH'
and its version number.kex_algs (
str
orlist
ofstr
) – (optional) A list of allowed key exchange algorithms in the SSH handshake, taken from key exchange algorithms.encryption_algs (
str
orlist
ofstr
) – (optional) A list of encryption algorithms to use during the SSH handshake, taken from encryption algorithms.mac_algs (
str
orlist
ofstr
) – (optional) A list of MAC algorithms to use during the SSH handshake, taken from MAC algorithms.compression_algs (
str
orlist
ofstr
) – (optional) A list of compression algorithms to use during the SSH handshake, taken from compression algorithms, orNone
to disable compression.signature_algs (
str
orlist
ofstr
) – (optional) A list of public key signature algorithms to use during the SSH handshake, taken from signature algorithms.rekey_bytes (see Specifying byte counts) – (optional) The number of bytes which can be sent before the SSH session key is renegotiated. This defaults to 1 GB.
rekey_seconds (see Specifying time intervals) – (optional) The maximum time in seconds before the SSH session key is renegotiated. This defaults to 1 hour.
connect_timeout (see Specifying time intervals) – (optional) The maximum time in seconds allowed to complete an outbound SSH connection. This includes the time to establish the TCP connection and the time to perform the initial SSH protocol handshake, key exchange, and authentication. This is disabled by default, relying on the system’s default TCP connect timeout and AsyncSSH’s login timeout.
login_timeout (see Specifying time intervals) –
(optional) The maximum time in seconds allowed for authentication to complete, defaulting to 2 minutes. Setting this to 0 will disable the login timeout.
Note
This timeout only applies after the SSH TCP connection is established. To set a timeout which includes establishing the TCP connection, use the
connect_timeout
argument above.keepalive_interval (see Specifying time intervals) – (optional) The time in seconds to wait before sending a keepalive message if no data has been received from the server. This defaults to 0, which disables sending these messages.
keepalive_count_max (
int
) – (optional) The maximum number of keepalive messages which will be sent without getting a response before disconnecting from the server. This defaults to 3, but only applies when keepalive_interval is non-zero.command (
str
) – (optional) The default remote command to execute on client sessions. An interactive shell is started if no command or subsystem is specified.subsystem (
str
) – (optional) The default remote subsystem to start on client sessions.env (
dict
withstr
keys and values) –(optional) The default environment variables to set for client sessions. 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.
send_env (
list
ofstr
) – (optional) A list of environment variable names to pull fromos.environ
and set by default for client sessions. Wildcards patterns using'*'
and'?'
are allowed, and all variables with matching names will be sent with whatever value is set in the local environment. If a variable is present in both env and send_env, the value from env will be used.request_pty (
bool
,'force'
, or'auto'
) – (optional) Whether or not to request a pseudo-terminal (PTY) by default for client sessions. This defaults toTrue
, which means to request a PTY whenever theterm_type
is set. Other possible values includeFalse
to never request a PTY,'force'
to always request a PTY even withoutterm_type
being set, or'auto'
to request a TTY whenterm_type
is set but only when starting an interactive shell.term_type (
str
) – (optional) The default terminal type to set for client sessions.term_size (
tuple
of 2 or 4int
values) – (optional) The terminal width and height in characters and optionally the width and height in pixels to set for client sessions.term_modes (
dict
withint
keys and values) – (optional) POSIX terminal modes to set for client sessions, where keys are taken from POSIX terminal modes with values defined in section 8 of RFC 4254.x11_forwarding (
bool
or'ignore_failure'
) – (optional) Whether or not to request X11 forwarding for client sessions, defaulting toFalse
. If set toTrue
, X11 forwarding will be requested and a failure will raiseChannelOpenError
. It can also be set to'ignore_failure'
to attempt X11 forwarding but ignore failures.x11_display (
str
) – (optional) The display that X11 connections should be forwarded to, defaulting to the value in the environment variableDISPLAY
.x11_auth_path (
str
) – (optional) The path to the Xauthority file to read X11 authentication data from, defaulting to the value in the environment variableXAUTHORITY
or the file.Xauthority
in the user’s home directory if that’s not set.x11_single_connection (
bool
) – (optional) Whether or not to limit X11 forwarding to a single connection, defaulting toFalse
.encoding (
str
orNone
) – (optional) The default Unicode encoding to use for data exchanged on client sessions.errors (
str
) – (optional) The default error handling strategy to apply on Unicode encode/decode errors.window (
int
) – (optional) The default receive window size to set for client sessions.max_pktsize (
int
) – (optional) The default maximum packet size to set for client sessions.(optional) Paths to OpenSSH client configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options.
Note
Specifying configuration files when creating an
SSHClientConnectionOptions
object will cause the config file to be read and parsed at the time of creation of the object, including evaluation of any conditional blocks. If you want the config to be parsed for every new connection, this argument should be added to the connect or listen calls instead. However, if you want to save the parsing overhead and your configuration doesn’t depend on conditions that would change between calls, this argument may be an option.options (
SSHClientConnectionOptions
) – (optional) A previous set of options to use as the base to incrementally build up a configuration. When an option is not explicitly specified, its value will be pulled from this options object (if present) before falling back to the default value.
SSHServerConnectionOptions¶
- class asyncssh.SSHServerConnectionOptions[source]¶
SSH server connection options
The following options are available to control the acceptance of SSH server connections:
- Parameters
server_factory (
callable
returningSSHServer
) – Acallable
which returns anSSHServer
object that will be created for each new connection.proxy_command (
str
orlist
ofstr
) – (optional) A string or list of strings specifying a command and arguments to run when usingconnect_reverse()
to make a reverse direction connection to an SSH client. Data will be forwarded to this process over stdin/stdout instead of opening a TCP connection. If specified as a string, standard shell quoting will be applied when splitting the command and its arguments.server_host_keys (see Specifying private keys) – (optional) A list of private keys and optional certificates which can be used by the server as a host key. Either this argument or
gss_host
must be specified. If this is not specified, only GSS-based key exchange will be supported.server_host_certs (see Specifying certificates) – (optional) A list of optional certificates which can be paired with the provided server host keys.
passphrase (
str
orbytes
) – (optional) The passphrase to use to decrypt server host keys when loading them, if they are encrypted. If this is not specified, only unencrypted server host keys can be loaded. If the keys passed into server_host_keys are already loaded, this argument is ignored.known_client_hosts (see Specifying known hosts) – (optional) A list of client hosts which should be trusted to perform host-based client authentication. If this is not specified, host-based client authentication will be not be performed.
trust_client_host (
bool
) – (optional) Whether or not to use the hostname provided by the client when performing host-based authentication. By default, the client-provided hostname is not trusted and is instead determined by doing a reverse lookup of the IP address the client connected from.authorized_client_keys (see Specifying authorized keys) – (optional) A list of authorized user and CA public keys which should be trusted for certificate-based client public key authentication.
x509_trusted_certs (see Specifying certificates) –
(optional) A list of certificates which should be trusted for X.509 client certificate authentication. If this argument is explicitly set to
None
, X.509 client certificate authentication will not be performed.Note
X.509 certificates to trust can also be provided through an authorized_keys file if they are converted into OpenSSH format. This allows their trust to be limited to only specific client IPs or user names and allows SSH functions to be restricted when these certificates are used.
x509_trusted_cert_paths (
list
ofstr
) – (optional) A list of path names to “hash directories” containing certificates which should be trusted for X.509 client certificate authentication. Each certificate should be in a separate file with a name of the form hash.number, where hash is the OpenSSL hash value of the certificate subject name and number is an integer counting up from zero if multiple certificates have the same hash.x509_purposes (see Specifying X.509 purposes) – (optional) A list of purposes allowed in the ExtendedKeyUsage of a certificate used for X.509 client certificate authentication, defulting to ‘secureShellClient’. If this argument is explicitly set to
None
, the client certificate’s ExtendedKeyUsage will not be checked.host_based_auth (
bool
) – (optional) Whether or not to allow host-based authentication. By default, host-based authentication is enabled if known client host keys are specified or if callbacks to validate client host keys are made available.public_key_auth (
bool
) – (optional) Whether or not to allow public key authentication. By default, public key authentication is enabled if authorized client keys are specified or if callbacks to validate client keys are made available.kbdint_auth (
bool
) – (optional) Whether or not to allow keyboard-interactive authentication. By default, keyboard-interactive authentication is enabled if the callbacks to generate challenges are made available.password_auth (
bool
) – (optional) Whether or not to allow password authentication. By default, password authentication is enabled if callbacks to validate a password are made available.gss_host (
str
) – (optional) The principal name to use for the host in GSS key exchange and authentication. If not specified, the value returned bysocket.gethostname()
will be used if it is a fully qualified name. Otherwise, the value used bysocket.getfqdn()
will be used. If this argument is explicitly set toNone
, GSS key exchange and authentication will not be performed.gss_kex (
bool
) – (optional) Whether or not to allow GSS key exchange. By default, GSS key exchange is enabled.gss_auth (
bool
) – (optional) Whether or not to allow GSS authentication. By default, GSS authentication is enabled.allow_pty (
bool
) – (optional) Whether or not to allow allocation of a pseudo-tty in sessions, defaulting toTrue
line_editor (
bool
) – (optional) Whether or not to enable input line editing on sessions which have a pseudo-tty allocated, defaulting toTrue
line_echo (
bool
) – (bool) Whether or not to echo completed input lines when they are entered, rather than waiting for the application to read and echo them, defaulting toTrue
. Setting this toFalse
and performing the echo in the application can better synchronize input and output, especially when there are input prompts.line_history (
int
) – (int) The number of lines of input line history to store in the line editor when it is enabled, defaulting to 1000max_line_length (
int
) – (int) The maximum number of characters allowed in an input line when the line editor is enabled, defaulting to 1024rdns_lookup (
bool
) – (optional) Whether or not to perform reverse DNS lookups on the client’s IP address to enable hostname-based matches in authorized key file “from” options and “Match Host” config options, defaulting toFalse
.x11_forwarding (
bool
) – (optional) Whether or not to allow forwarding of X11 connections back to the client when the client supports it, defaulting toFalse
x11_auth_path (
str
) – (optional) The path to the Xauthority file to write X11 authentication data to, defaulting to the value in the environment variableXAUTHORITY
or the file.Xauthority
in the user’s home directory if that’s not setagent_forwarding (
bool
) – (optional) Whether or not to allow forwarding of ssh-agent requests back to the client when the client supports it, defaulting toTrue
process_factory (
callable
or coroutine) – (optional) Acallable
or coroutine handler function which takes an AsyncSSHSSHServerProcess
argument that will be called each time a new shell, exec, or subsystem other than SFTP is requested by the client. If set, this takes precedence over thesession_factory
argument.session_factory (
callable
or coroutine) – (optional) Acallable
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 subsystem other than SFTP is requested by the client. If not specified, sessions are rejected by default unless thesession_requested()
method is overridden on theSSHServer
object returned byserver_factory
to make this decision.encoding (
str
orNone
) – (optional) The Unicode encoding to use for data exchanged on sessions on this server, defaulting to UTF-8 (ISO 10646) format. IfNone
is passed in, the application can send and receive raw bytes.errors (
str
) – (optional) The error handling strategy to apply on Unicode encode/decode errors of data exchanged on sessions on this server, defaulting to ‘strict’.sftp_factory (
callable
) – (optional) Acallable
which returns anSFTPServer
object that will be created each time an SFTP session is requested by the client, orTrue
to use the baseSFTPServer
class to handle SFTP requests. If not specified, SFTP sessions are rejected by default.sftp_version (
int
) – (optional) The maximum version of the SFTP protocol to support, currently either 3 or 4, defaulting to 3.allow_scp (
bool
) – (optional) Whether or not to allow incoming scp requests to be accepted. This option can only be used in conjunction withsftp_factory
. If not specified, scp requests will be passed as regular commands to theprocess_factory
orsession_factory
. to the client when the client supports it, defaulting toTrue
window (
int
) – (optional) The receive window size for sessions on this servermax_pktsize (
int
) – (optional) The maximum packet size for sessions on this serverserver_version (
str
) – (optional) An ASCII string to advertise to SSH clients as the version of this server, defaulting to'AsyncSSH'
and its version number.kex_algs (
str
orlist
ofstr
) – (optional) A list of allowed key exchange algorithms in the SSH handshake, taken from key exchange algorithmsencryption_algs (
str
orlist
ofstr
) – (optional) A list of encryption algorithms to use during the SSH handshake, taken from encryption algorithmsmac_algs (
str
orlist
ofstr
) – (optional) A list of MAC algorithms to use during the SSH handshake, taken from MAC algorithmscompression_algs (
str
orlist
ofstr
) – (optional) A list of compression algorithms to use during the SSH handshake, taken from compression algorithms, orNone
to disable compressionsignature_algs (
str
orlist
ofstr
) – (optional) A list of public key signature algorithms to use during the SSH handshake, taken from signature algorithmsrekey_bytes (see Specifying byte counts) – (optional) The number of bytes which can be sent before the SSH session key is renegotiated, defaulting to 1 GB
rekey_seconds (see Specifying time intervals) – (optional) The maximum time in seconds before the SSH session key is renegotiated, defaulting to 1 hour
connect_timeout (see Specifying time intervals) – (optional) The maximum time in seconds allowed to complete an outbound SSH connection. This includes the time to establish the TCP connection and the time to perform the initial SSH protocol handshake, key exchange, and authentication. This is disabled by default, relying on the system’s default TCP connect timeout and AsyncSSH’s login timeout.
login_timeout (see Specifying time intervals) –
(optional) The maximum time in seconds allowed for authentication to complete, defaulting to 2 minutes. Setting this to 0 will disable the login timeout.
Note
This timeout only applies after the SSH TCP connection is established. To set a timeout which includes establishing the TCP connection, use the
connect_timeout
argument above.keepalive_interval (see Specifying time intervals) – (optional) The time in seconds to wait before sending a keepalive message if no data has been received from the client. This defaults to 0, which disables sending these messages.
keepalive_count_max (
int
) – (optional) The maximum number of keepalive messages which will be sent without getting a response before disconnecting a client. This defaults to 3, but only applies when keepalive_interval is non-zero.tcp_keepalive – (optional) Whether or not to enable keepalive probes at the TCP level to detect broken connections, defaulting to
True
(optional) Paths to OpenSSH server configuration files to load. This configuration will be used as a fallback to override the defaults for settings which are not explicitly specified using AsyncSSH’s configuration options.
Note
Specifying configuration files when creating an
SSHServerConnectionOptions
object will cause the config file to be read and parsed at the time of creation of the object, including evaluation of any conditional blocks. If you want the config to be parsed for every new connection, this argument should be added to the connect or listen calls instead. However, if you want to save the parsing overhead and your configuration doesn’t depend on conditions that would change between calls, this argument may be an option.options (
SSHServerConnectionOptions
) – (optional) A previous set of options to use as the base to incrementally build up a configuration. When an option is not explicitly specified, its value will be pulled from this options object (if present) before falling back to the default value.
Process Classes¶
SSHClientProcess¶
- class asyncssh.SSHClientProcess[source]¶
SSH client process handler
Client process attributes
- channel¶
The channel associated with the process
- logger¶
The logger associated with the process
- env¶
A mapping containing the environment set by the client
- exit_status¶
The exit status of the process
- exit_signal¶
Exit signal information for the process
- returncode¶
The exit status or negative exit signal number for the process
Other client process methods
- get_extra_info(name, default=None)¶
Return additional information about this process
This method returns extra information about the channel associated with this process. See
get_extra_info()
onSSHClientChannel
for additional information.
- async redirect(stdin=None, stdout=None, stderr=None, bufsize=8192, send_eof=True, recv_eof=True)[source]¶
Perform I/O redirection for the process
This method redirects data going to or from any or all of standard input, standard output, and standard error for the process.
The
stdin
argument can be any of the following:An
SSHReader
objectAn
asyncio.StreamReader
objectA file object open for read
An
int
file descriptor open for readA connected socket object
A string or
PurePath
containing the name of a file or device to openDEVNULL
to provide no input to standard inputPIPE
to interactively write standard input
The
stdout
andstderr
arguments can be any of the following:An
SSHWriter
objectAn
asyncio.StreamWriter
objectA file object open for write
An
int
file descriptor open for writeA connected socket object
A string or
PurePath
containing the name of a file or device to openDEVNULL
to discard standard error outputPIPE
to interactively read standard error output
The
stderr
argument also accepts the valueSTDOUT
to request that standard error output be delivered to stdout.File objects passed in can be associated with plain files, pipes, sockets, or ttys.
The default value of
None
means to not change redirection for that stream.Note
When passing in asyncio streams, it is the responsibility of the caller to close the associated transport when it is no longer needed.
- Parameters
stdin – Source of data to feed to standard input
stdout – Target to feed data from standard output to
stderr – Target to feed data from standard error to
bufsize (
int
) – Buffer size to use when forwarding data from a filesend_eof (
bool
) – Whether or not to send EOF to the channel when EOF is received from stdin, defaulting toTrue
. If set toFalse
, the channel will remain open after EOF is received on stdin, and multiple sources can be redirected to the channel.recv_eof (
bool
) – Whether or not to send EOF to stdout and stderr when EOF is received from the channel, defaulting toTrue
. If set toFalse
, the redirect targets of stdout and stderr will remain open after EOF is received on the channel and can be used for multiple redirects.
- collect_output()[source]¶
Collect output from the process without blocking
This method returns a tuple of the output that the process has written to stdout and stderr which has not yet been read. It is intended to be called instead of read() by callers that want to collect received data without blocking.
- Returns
A tuple of output to stdout and stderr
- async wait(check=False, timeout=None)[source]¶
Wait for process to exit
This method is a coroutine which waits for the process to exit. It returns an
SSHCompletedProcess
object with the exit status or signal information and the output sent to stdout and stderr if those are redirected to pipes.If the check argument is set to
True
, a non-zero exit status from the process with trigger theProcessError
exception to be raised.If a timeout is specified and it expires before the process exits, the
TimeoutError
exception will be raised. By default, no timeout is set and this call will wait indefinitely.- Parameters
- Returns
- Raises
ProcessError
if check is set toTrue
and the process returns a non-zero exit statusTimeoutError
if the timeout expires before the process exits
Client process close methods
- close()¶
Shut down the process
- is_closing()¶
Return if the channel is closing or is closed
- async wait_closed()¶
Wait for the process to finish shutting down
SSHServerProcess¶
- class asyncssh.SSHServerProcess(process_factory, sftp_factory, sftp_version, allow_scp)[source]¶
SSH server process handler
Server process attributes
- channel¶
The channel associated with the process
- logger¶
The logger associated with the process
- env¶
A mapping containing the environment set by the client
- term_size¶
The terminal size set by the client
This property contains a tuple of four
int
values representing the width and height of the terminal in characters followed by the width and height of the terminal in pixels. If the client hasn’t set terminal size information, the values will be set to zero.
- term_modes¶
A mapping containing the TTY modes set by the client
If the client didn’t request a pseudo-terminal, this property will be set to an empty mapping.
Other server process methods
- get_extra_info(name, default=None)¶
Return additional information about this process
This method returns extra information about the channel associated with this process. See
get_extra_info()
onSSHClientChannel
for additional information.
- async redirect(stdin=None, stdout=None, stderr=None, bufsize=8192, send_eof=True, recv_eof=True)[source]¶
Perform I/O redirection for the process
This method redirects data going to or from any or all of standard input, standard output, and standard error for the process.
The
stdin
argument can be any of the following:An
SSHWriter
objectAn
asyncio.StreamWriter
objectA file object open for write
An
int
file descriptor open for writeA connected socket object
A string or
PurePath
containing the name of a file or device to openDEVNULL
to discard standard error outputPIPE
to interactively read standard error output
The
stdout
andstderr
arguments can be any of the following:An
SSHReader
objectAn
asyncio.StreamReader
objectA file object open for read
An
int
file descriptor open for readA connected socket object
A string or
PurePath
containing the name of a file or device to openDEVNULL
to provide no input to standard inputPIPE
to interactively write standard input
File objects passed in can be associated with plain files, pipes, sockets, or ttys.
The default value of
None
means to not change redirection for that stream.Note
When passing in asyncio streams, it is the responsibility of the caller to close the associated transport when it is no longer needed.
- Parameters
stdin – Target to feed data from standard input to
stdout – Source of data to feed to standard output
stderr – Source of data to feed to standard error
bufsize (
int
) – Buffer size to use when forwarding data from a filesend_eof (
bool
) – Whether or not to send EOF to the channel when EOF is received from stdout or stderr, defaulting toTrue
. If set toFalse
, the channel will remain open after EOF is received on stdout or stderr, and multiple sources can be redirected to the channel.recv_eof (
bool
) – Whether or not to send EOF to stdin when EOF is received on the channel, defaulting toTrue
. If set toFalse
, the redirect target of stdin will remain open after EOF is received on the channel and can be used for multiple redirects.
Server process close methods
- exit_with_signal(signal, core_dumped=False, msg='', lang='en-US')[source]¶
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.
- close()¶
Shut down the process
- is_closing()¶
Return if the channel is closing or is closed
- async wait_closed()¶
Wait for the process to finish shutting down
SSHCompletedProcess¶
- class asyncssh.SSHCompletedProcess[source]¶
Results from running an SSH process
This object is returned by the
run
method onSSHClientConnection
when the requested command has finished running. It contains the following fields:Field
Description
Type
env
The environment the client requested to be set for the process
command
The command the client requested the process to execute (if any)
subsystem
The subsystem the client requested the process to open (if any)
exit_status
The exit status returned, or -1 if an exit signal is sent
exit_signal
The exit signal sent (if any) in the form of a tuple containing the signal name, a
bool
for whether a core dump occurred, a message associated with the signal, and the language the message was inreturncode
The exit status returned, or negative of the signal number when an exit signal is sent
stdout
The output sent by the process to stdout (if not redirected)
stderr
The output sent by the process to stderr (if not redirected)
SSHSubprocessReadPipe¶
- class asyncssh.SSHSubprocessReadPipe[source]¶
SSH subprocess pipe reader
General subprocess pipe info methods
- get_extra_info(name, default=None)¶
Return additional information about the remote process
This method returns extra information about the channel associated with this subprocess. See
get_extra_info()
onSSHClientChannel
for additional information.
Subprocess pipe read methods
General subprocess pipe close methods
- close()¶
Shut down the remote process
SSHSubprocessWritePipe¶
- class asyncssh.SSHSubprocessWritePipe[source]¶
SSH subprocess pipe writer
General subprocess pipe info methods
- get_extra_info(name, default=None)¶
Return additional information about the remote process
This method returns extra information about the channel associated with this subprocess. See
get_extra_info()
onSSHClientChannel
for additional information.
Subprocess pipe write methods
- can_write_eof()[source]¶
Return whether the pipe supports
write_eof()
General subprocess pipe close methods
- close()¶
Shut down the remote process
SSHSubprocessProtocol¶
- class asyncssh.SSHSubprocessProtocol[source]¶
SSH subprocess protocol
This class conforms to
asyncio.SubprocessProtocol
, but with the following enhancement:If encoding is set when the subprocess is created, all data passed to
pipe_data_received()
will be string values containing Unicode data. However, for compatibility withasyncio.SubprocessProtocol
, encoding defaults toNone
, in which case all data is delivered as bytes.
General subprocess protocol handlers
- connection_made(transport)[source]¶
Called when a remote process is successfully started
This method is called when a remote process is successfully started. The transport parameter should be stored if needed for later use.
- Parameters
transport (
SSHSubprocessTransport
) – The transport to use to communicate with the remote process.
Subprocess protocol read handlers
- pipe_data_received(fd, data)[source]¶
Called when data is received from the remote process
This method is called when data is received from the remote process. If an encoding was specified when the process was started, the data will be delivered as a string after decoding with the requested encoding. Otherwise, the data will be delivered as bytes.
Other subprocess protocol handlers
- process_exited()[source]¶
Called when a remote process has exited
This method is called when the remote process has exited. Exit status information can be retrieved by calling
get_returncode()
on the transport provided inconnection_made()
.
SSHSubprocessTransport¶
- class asyncssh.SSHSubprocessTransport(protocol_factory)[source]¶
SSH subprocess transport
This class conforms to
asyncio.SubprocessTransport
, but with the following enhancements:All functionality available through
SSHClientProcess
is also available here, such as the ability to dynamically redirect stdin, stdout, and stderr at any time during the lifetime of the process.If encoding is set when the subprocess is created, all data written to the transports created by
get_pipe_transport()
should be strings containing Unicode data. The encoding defaults toNone
, though, to preserve compatibility withasyncio.SubprocessTransport
, which expects data to be written as bytes.
General subprocess transport methods
- get_extra_info(name, default=None)¶
Return additional information about this process
This method returns extra information about the channel associated with this process. See
get_extra_info()
onSSHClientChannel
for additional information.
- get_returncode()[source]¶
Return the exit status or signal for the remote process
This method returns the exit status of the session if one has been sent. If an exit signal was sent, this method returns the negative of the numeric value of that signal, matching the behavior of
asyncio.SubprocessTransport.get_returncode()
. If neither has been sent, this method returnsNone
.
- change_terminal_size(width, height, pixwidth=0, pixheight=0)¶
Change the terminal window size for this process
This method changes the width and height of the terminal associated with this process.
Subprocess transport close methods
- close()¶
Shut down the process
- is_closing()¶
Return if the channel is closing or is closed
- async wait_closed()¶
Wait for the process to finish shutting down
Session Classes¶
SSHClientSession¶
- class asyncssh.SSHClientSession[source]¶
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 asconnection_made()
,connection_lost()
,data_received()
,eof_received()
,pause_writing()
, andresume_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, andexit_status_received()
andexit_signal_received()
can be used to receive session exit information.General session handlers
- connection_made(chan)[source]¶
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.
- 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 and UNIX domain socket 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
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 for classes derived directly fromSSHSession
, but not when using the higher-level streams API. Because input is buffered in that case, streaming sessions enable half-open channels to allow applications to respond to input read after an end-of-file indication is received.
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)[source]¶
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 isFalse
, 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 (
bool
) – Whether or not to enable XON/XOFF flow control
- exit_status_received(status)[source]¶
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 (
int
) – The exit status returned by the remote process
- exit_signal_received(signal, core_dumped, msg, lang)[source]¶
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.
SSHServerSession¶
- class asyncssh.SSHServerSession[source]¶
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 asconnection_made()
,connection_lost()
,data_received()
,eof_received()
,pause_writing()
, andresume_writing()
are all supported. In addition,pty_requested()
is called when the client requests a pseudo-terminal, one ofshell_requested()
,exec_requested()
, orsubsystem_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, andbreak_received()
is called when the client sends a break.General session handlers
- connection_made(chan)[source]¶
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 (
SSHServerChannel
) – The channel which was successfully opened.
- 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 and UNIX domain socket sessions, it will be called immediately after the connection is opened.
Server session open handlers
- pty_requested(term_type, term_size, term_modes)[source]¶
A pseudo-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 returnFalse
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 callget_terminal_type()
,get_terminal_size()
, orget_terminal_mode()
on theSSHServerChannel
to get the information they need after a shell, command, or subsystem is started.- Parameters
term_type (
str
) – Terminal type to set for this sessionterm_size (tuple of 4
int
values) – Terminal size to set for this session provided as a tuple of fourint
values: the width and height of the terminal in characters followed by the width and height of the terminal in pixelsterm_modes (
dict
) – 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.
- Returns
A
bool
indicating if the request for a pseudo-terminal was allowed or not
- shell_requested()[source]¶
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, orFalse
to reject it.If the application returns
True
, thesession_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
bool
indicating if the shell request was allowed or not
- exec_requested(command)[source]¶
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, orFalse
to reject it.If the application returns
True
, thesession_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.
- subsystem_requested(subsystem)[source]¶
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, orFalse
to reject it.If the application returns
True
, thesession_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.
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
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 for classes derived directly fromSSHSession
, but not when using the higher-level streams API. Because input is buffered in that case, streaming sessions enable half-open channels to allow applications to respond to input read after an end-of-file indication is received.
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)[source]¶
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 returnFalse
.By default, this method returns
False
indicating that no break was performed.
- terminal_size_changed(width, height, pixwidth, pixheight)[source]¶
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.
SSHTCPSession¶
- class asyncssh.SSHTCPSession[source]¶
SSH TCP 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 theirSSHClientConnection
, passing in a factory which returns instances of this class.Server applications wishing to allow direct connections should implement the coroutine
connection_requested()
on theirSSHServer
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 theirSSHServer
object and callcreate_connection()
on theirSSHServerConnection
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 thedata_received()
method.General session handlers
- connection_made(chan)[source]¶
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 (
SSHTCPChannel
) – The channel which was successfully opened.
- 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 and UNIX domain socket 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
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 for classes derived directly fromSSHSession
, but not when using the higher-level streams API. Because input is buffered in that case, streaming sessions enable half-open channels to allow applications to respond to input read after an end-of-file indication is received.
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.
SSHUNIXSession¶
- class asyncssh.SSHUNIXSession[source]¶
SSH UNIX domain socket session handler
Applications should subclass this when implementing a handler for SSH direct or forwarded UNIX domain socket connections.
SSH client applications wishing to open a direct connection should call
create_unix_connection()
on theirSSHClientConnection
, passing in a factory which returns instances of this class.Server applications wishing to allow direct connections should implement the coroutine
unix_connection_requested()
on theirSSHServer
object and have it return instances of this class.Server applications wishing to allow connection forwarding back to the client should implement the coroutine
unix_server_requested()
on theirSSHServer
object and callcreate_unix_connection()
on theirSSHServerConnection
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 thedata_received()
method.General session handlers
- connection_made(chan)[source]¶
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 (
SSHUNIXChannel
) – The channel which was successfully opened.
- 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 and UNIX domain socket 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
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 for classes derived directly fromSSHSession
, but not when using the higher-level streams API. Because input is buffered in that case, streaming sessions enable half-open channels to allow applications to respond to input read after an end-of-file indication is received.
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[source]¶
SSH client channel
Channel attributes
- logger¶
A logger associated with this channel
General channel info 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.For UNIX channels, the values
'local_peername'
and'remote_peername'
are added to return the local and remote path information for the tunneled UNIX domain socket connection. Since UNIX domain sockets provide no “source” address, only one of these will be filled in.See
get_extra_info()
onSSHClientConnection
for more information.Additional information stored on the channel by calling
set_extra_info()
can also be returned here.
- set_extra_info(**kwargs)¶
Store additional information associated with the channel
This method allows extra information to be associated with the channel. The information to store should be passed in as keyword parameters and can later be returned by calling
get_extra_info()
with one of the keywords as the name to retrieve.
- get_environment()¶
Return the environment for this session
This method returns the environment set by the client when the session was opened. On the server, calls to this method should only be made after
session_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.- 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
. On the server, calls to this method should only be made aftersession_started
has been called on theSSHServerSession
. 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
. On the server, calls to this method should only be made aftersession_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.
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 notification 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()
andresume_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 tostderr
.- Parameters
datatype (
int
) – (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
str
orbytes
) – The data to send on the channeldatatype (
int
) – (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
Other client channel methods
- get_exit_status()[source]¶
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 sent, this method returns -1 and the exit signal information can be collected by calling
get_exit_signal()
. If neither has been sent, this method returnsNone
.
- get_exit_signal()[source]¶
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. Otherwise, this method returns
None
.
- get_returncode()[source]¶
Return the session’s exit status or signal
This method returns the exit status of the session if one has been sent. If an exit signal was sent, this method returns the negative of the numeric value of that signal, matching the behavior of
asyncio.SubprocessTransport.get_returncode()
. If neither has been sent, this method returnsNone
.
- send_signal(signal)[source]¶
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, or can be integer values as defined in the
signal
module, in which case they will be translated to their corresponding signal name before being sent.Note
OpenSSH’s SSH server implementation prior to version 7.9 does not support this message, so attempts to use
send_signal()
,terminate()
, orkill()
with an older OpenSSH SSH server will end up being ignored. This was tracked in OpenSSH bug 1424.- Parameters
- Raises
OSError
if the channel is not openValueError
if the signal number is unknown
- kill()[source]¶
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
Note
If your server-side runs on OpenSSH, this might be ineffective; for more details, see the note in
send_signal()
- terminate()[source]¶
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
Note
If your server-side runs on OpenSSH, this might be ineffective; for more details, see the note in
send_signal()
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.
- is_closing()¶
Return if the channel is closing or is closed
- async 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[source]¶
SSH server channel
Channel attributes
- logger¶
A logger associated with this channel
General channel info 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.For UNIX channels, the values
'local_peername'
and'remote_peername'
are added to return the local and remote path information for the tunneled UNIX domain socket connection. Since UNIX domain sockets provide no “source” address, only one of these will be filled in.See
get_extra_info()
onSSHClientConnection
for more information.Additional information stored on the channel by calling
set_extra_info()
can also be returned here.
- set_extra_info(**kwargs)¶
Store additional information associated with the channel
This method allows extra information to be associated with the channel. The information to store should be passed in as keyword parameters and can later be returned by calling
get_extra_info()
with one of the keywords as the name to retrieve.
- get_environment()¶
Return the environment for this session
This method returns the environment set by the client when the session was opened. On the server, calls to this method should only be made after
session_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.- 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
. On the server, calls to this method should only be made aftersession_started
has been called on theSSHServerSession
. 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
. On the server, calls to this method should only be made aftersession_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.
Server channel info methods
- get_terminal_type()[source]¶
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 aftersession_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.
- get_terminal_size()[source]¶
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 theSSHServerSession
. 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 theTerminalSizeChanged
exception for how to get notified when the terminal size changes.- Returns
A tuple of four
int
values containing the width and height of the terminal in characters and the width and height of the terminal in pixels
- get_terminal_mode(mode)[source]¶
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 aftersession_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.- Parameters
mode (
int
) – POSIX terminal mode taken from POSIX terminal modes to look up- Returns
An
int
containing the value of the requested POSIX terminal mode orNone
if the requested mode was not set
- get_terminal_modes()[source]¶
Return the TTY modes for this session
This method returns a mapping of all the POSIX terminal modes set by the client when the session was opened. If the client didn’t request a pseudo-terminal, this method will return an empty mapping. Calls to this method should only be made after
session_started
has been called on theSSHServerSession
. When using the stream-based API, calls to this can be made at any time after the handler function has started up.- returns
A mapping containing all the POSIX terminal modes set by the client or an empty mapping if no pseudo-terminal was requested
- get_agent_path()[source]¶
Return the path of the ssh-agent listening socket
When agent forwarding has been requested by the client, this method returns the path of the listening socket which should be used to open a forwarded agent connection. If the client did not request agent forwarding, this method returns
None
.
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 notification 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()
andresume_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 tostderr
.- Parameters
datatype (
int
) – (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
str
orbytes
) – The data to send on the channeldatatype (
int
) – (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)[source]¶
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.
- writelines_stderr(list_of_data)[source]¶
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.
Other server channel methods
- set_xon_xoff(client_can_do)[source]¶
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 toFalse
to tell the client to forward Control-S and Control-Q through as normal input.- Parameters
client_can_do (
bool
) – Whether or not the client should enable XON/XOFF flow control
- exit_with_signal(signal, core_dumped=False, msg='', lang='en-US')[source]¶
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.
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.
- is_closing()¶
Return if the channel is closing or is closed
- async 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.
SSHLineEditorChannel¶
- class asyncssh.SSHLineEditorChannel[source]¶
Input line editor channel wrapper
When creating server channels with
line_editor
set toTrue
, this class is wrapped around the channel, providing the caller with the ability to enable and disable input line editing and echoing.Note
Line editing is only available when a pseudo-terminal is requested on the server channel and the character encoding on the channel is not set to
None
.Line editor methods
- register_key(key, handler)[source]¶
Register a handler to be called when a key is pressed
This method registers a handler function which will be called when a user presses the specified key while inputting a line.
The handler will be called with arguments of the current input line and cursor position, and updated versions of these two values should be returned as a tuple.
The handler can also return a tuple of a signal name and negative cursor position to cause a signal to be delivered on the channel. In this case, the current input line is left unchanged but the signal is delivered before processing any additional input. This can be used to define “hot keys” that trigger actions unrelated to editing the input.
If the registered key is printable text, returning
True
will insert that text at the current cursor position, acting as if no handler was registered for that key. This is useful if you want to perform a special action in some cases but not others, such as based on the current cursor position.Returning
False
will ring the bell and leave the input unchanged, indicating the requested action could not be performed.
- unregister_key(key)[source]¶
Remove the handler associated with a key
This method removes a handler function associated with the specified key. If the key sequence is printable, this will cause it to return to being inserted at the current position when pressed. Otherwise, it will cause the bell to ring to signal the key is not understood.
- Parameters
key (
str
) – The key sequence to look for
- set_line_mode(line_mode)[source]¶
Enable/disable input line editing
This method enabled or disables input line editing. When set, only full lines of input are sent to the session, and each line of input can be edited before it is sent.
- Parameters
line_mode (
bool
) – Whether or not to process input a line at a time
SSHTCPChannel¶
- class asyncssh.SSHTCPChannel[source]¶
SSH TCP channel
Channel attributes
- logger¶
A logger associated with this channel
General channel info 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.For UNIX channels, the values
'local_peername'
and'remote_peername'
are added to return the local and remote path information for the tunneled UNIX domain socket connection. Since UNIX domain sockets provide no “source” address, only one of these will be filled in.See
get_extra_info()
onSSHClientConnection
for more information.Additional information stored on the channel by calling
set_extra_info()
can also be returned here.
- set_extra_info(**kwargs)¶
Store additional information associated with the channel
This method allows extra information to be associated with the channel. The information to store should be passed in as keyword parameters and can later be returned by calling
get_extra_info()
with one of the keywords as the name to retrieve.
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 notification 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()
andresume_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 tostderr
.- Parameters
datatype (
int
) – (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
str
orbytes
) – The data to send on the channeldatatype (
int
) – (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
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.
- is_closing()¶
Return if the channel is closing or is closed
- async 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.
SSHUNIXChannel¶
- class asyncssh.SSHUNIXChannel[source]¶
SSH UNIX channel
Channel attributes
- logger¶
A logger associated with this channel
General channel info 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.For UNIX channels, the values
'local_peername'
and'remote_peername'
are added to return the local and remote path information for the tunneled UNIX domain socket connection. Since UNIX domain sockets provide no “source” address, only one of these will be filled in.See
get_extra_info()
onSSHClientConnection
for more information.Additional information stored on the channel by calling
set_extra_info()
can also be returned here.
- set_extra_info(**kwargs)¶
Store additional information associated with the channel
This method allows extra information to be associated with the channel. The information to store should be passed in as keyword parameters and can later be returned by calling
get_extra_info()
with one of the keywords as the name to retrieve.
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 notification 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()
andresume_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 tostderr
.- Parameters
datatype (
int
) – (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
str
orbytes
) – The data to send on the channeldatatype (
int
) – (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
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.
- is_closing()¶
Return if the channel is closing or is closed
- async 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¶
SSHAcceptor¶
- class asyncssh.SSHAcceptor[source]¶
SSH acceptor
This class in a wrapper around an
asyncio.Server
listener which provides the ability to update the the set of SSH client or server connection options associated with that listener. This is accomplished by calling theupdate()
method, which takes the same keyword arguments as theSSHClientConnectionOptions
andSSHServerConnectionOptions
classes.In addition, this class supports all of the methods supported by
asyncio.Server
to control accepting of new connections.- get_addresses()[source]¶
Return socket addresses being listened on
This method returns the socket addresses being listened on. It returns tuples of the form returned by
socket.getsockname()
. If the listener was created using a hostname, the host’s resolved IPs will be returned. If the requested listening port was0
, the selected listening ports will be returned.- Returns
A list of socket addresses being listened on
- get_port()[source]¶
Return the port number being listened on
This method returns the port number being listened on. If it is listening on multiple sockets with different port numbers, this function will return
0
. In that case,get_addresses()
can be used to retrieve the full list of listening addresses and ports.- Returns
The port number being listened on, if there’s only one
- update(**kwargs)[source]¶
Update options on an SSH listener
Acceptors started by
listen()
support options defined inSSHServerConnectionOptions
. Acceptors started bylisten_reverse()
support options defined inSSHClientConnectionOptions
.Changes apply only to SSH client/server connections accepted after the change is made. Previously accepted connections will continue to use the options set when they were accepted.
SSHListener¶
- class asyncssh.SSHListener[source]¶
SSH listener for inbound connections
- get_port()[source]¶
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. This function only applies to TCP listeners.- Returns
The port number being listened on
Stream Classes¶
SSHReader¶
- class asyncssh.SSHReader[source]¶
SSH read stream handler
- channel¶
The SSH channel associated with this stream
- logger¶
The SSH logger associated with this stream
- get_extra_info(name, default=None)[source]¶
Return additional information about this stream
This method returns extra information about the channel associated with this stream. See
get_extra_info()
onSSHClientChannel
for additional information.
- feed_data(data)[source]¶
Feed data to the associated session
This method feeds data to the SSH session associated with this stream, providing compatibility with the
feed_data()
method onasyncio.StreamReader
. This is mostly useful for testing.
- feed_eof()[source]¶
Feed EOF to the associated session
This method feeds an end-of-file indication to the SSH session associated with this stream, providing compatibility with the
feed_eof()
method onasyncio.StreamReader
. This is mostly useful for testing.
- async read(n=- 1)[source]¶
Read data from the stream
This method is a coroutine which reads up to
n
bytes or characters from the stream. Ifn
is not provided or set to-1
, it reads until EOF or a signal is received.If EOF is received and the receive buffer is empty, an empty
bytes
orstr
object is returned.If the next data in the stream is a signal, the signal is delivered as a raised exception.
- async readline()[source]¶
Read one line from the stream
This method is a coroutine which reads one line, ending in
'n'
.If EOF is received before
'n'
is found, the partial line is returned. If EOF is received and the receive buffer is empty, an emptybytes
orstr
object is returned.If the next data in the stream is a signal, the signal is delivered as a raised exception.
Note
In Python 3.5 and later,
SSHReader
objects can also be used as async iterators, returning input data one line at a time.
- async readuntil(separator, max_separator_len=0)[source]¶
Read data from the stream until
separator
is seenThis method is a coroutine which reads from the stream until the requested separator is seen. If a match is found, the returned data will include the separator at the end.
The
separator
argument can be a singlebytes
orstr
value, a sequence of multiplebytes
orstr
values, or a compiled regex (re.Pattern
) to match against, returning data as soon as a matching separator is found in the stream.When passing a regex pattern as the separator, the
max_separator_len
argument should be set to the maximum length of an expected separator match. This can greatly improve performance, by minimizing how far back into the stream must be searched for a match. When passing literal separators to match against, the max separator length will be set automatically.Note
For best results, a separator regex should both begin and end with data which is as unique as possible, and should not start or end with optional or repeated elements. Otherwise, you run the risk of failing to match parts of a separator when it is split across multiple reads.
If EOF or a signal is received before a match occurs, an
IncompleteReadError
is raised and itspartial
attribute will contain the data in the stream prior to the EOF or signal.If the next data in the stream is a signal, the signal is delivered as a raised exception.
- async readexactly(n)[source]¶
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 or a signal is received in the stream before
n
bytes are read, anIncompleteReadError
is raised and itspartial
attribute will contain the data before the EOF or signal.If the next data in the stream is a signal, the signal is delivered as a raised exception.
SSHWriter¶
- class asyncssh.SSHWriter[source]¶
SSH write stream handler
- channel¶
The SSH channel associated with this stream
- logger¶
The SSH logger associated with this stream
- get_extra_info(name, default=None)[source]¶
Return additional information about this stream
This method returns extra information about the channel associated with this stream. See
get_extra_info()
onSSHClientChannel
for additional information.
- can_write_eof()[source]¶
Return whether the stream supports
write_eof()
- async drain()[source]¶
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_eof()[source]¶
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[source]¶
SFTP client
This class represents the client side of an SFTP session. It is started by calling the
start_sftp_client()
method on theSSHClientConnection
class.SFTP client attributes
- logger¶
A logger associated with this SFTP client
- version¶
SFTP version associated with this SFTP session
File transfer methods
- async get(remotepaths, localpath=None, *, preserve=False, recurse=False, follow_symlinks=False, block_size=16384, max_requests=128, progress_handler=None, error_handler=None)[source]¶
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.The block_size argument specifies the size of read and write requests issued when downloading the files, defaulting to 16 KB.
The max_requests argument specifies the maximum number of parallel read or write requests issued, defaulting to 128.
If progress_handler is specified, it will be called after each block of a file is successfully downloaded. The arguments passed to this handler will be the source path, destination path, bytes downloaded so far, and total bytes in the file being downloaded. If multiple source paths are provided or recurse is set to
True
, the progress_handler will be called consecutively on each file being downloaded.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 (
PurePath
,str
, orbytes
, or a sequence of these) – The paths of the remote files or directories to downloadlocalpath (
PurePath
,str
, orbytes
) – (optional) The path of the local file or directory to download intopreserve (
bool
) – (optional) Whether or not to preserve the original file attributesrecurse (
bool
) – (optional) Whether or not to recursively copy directoriesfollow_symlinks (
bool
) – (optional) Whether or not to follow symbolic linksblock_size (
int
) – (optional) The block size to use for file reads and writesmax_requests (
int
) – (optional) The maximum number of parallel read or write requestsprogress_handler (
callable
) – (optional) The function to call to report download progresserror_handler (
callable
) – (optional) The function to call when an error occurs
- Raises
- async put(localpaths, remotepath=None, *, preserve=False, recurse=False, follow_symlinks=False, block_size=16384, max_requests=128, progress_handler=None, error_handler=None)[source]¶
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.The block_size argument specifies the size of read and write requests issued when uploading the files, defaulting to 16 KB.
The max_requests argument specifies the maximum number of parallel read or write requests issued, defaulting to 128.
If progress_handler is specified, it will be called after each block of a file is successfully uploaded. The arguments passed to this handler will be the source path, destination path, bytes uploaded so far, and total bytes in the file being uploaded. If multiple source paths are provided or recurse is set to
True
, the progress_handler will be called consecutively on each file being uploaded.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 (
PurePath
,str
, orbytes
, or a sequence of these) – The paths of the local files or directories to uploadremotepath (
PurePath
,str
, orbytes
) – (optional) The path of the remote file or directory to upload intopreserve (
bool
) – (optional) Whether or not to preserve the original file attributesrecurse (
bool
) – (optional) Whether or not to recursively copy directoriesfollow_symlinks (
bool
) – (optional) Whether or not to follow symbolic linksblock_size (
int
) – (optional) The block size to use for file reads and writesmax_requests (
int
) – (optional) The maximum number of parallel read or write requestsprogress_handler (
callable
) – (optional) The function to call to report upload progresserror_handler (
callable
) – (optional) The function to call when an error occurs
- Raises
- async copy(srcpaths, dstpath=None, *, preserve=False, recurse=False, follow_symlinks=False, block_size=16384, max_requests=128, progress_handler=None, error_handler=None)[source]¶
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.The block_size argument specifies the size of read and write requests issued when copying the files, defaulting to 16 KB.
The max_requests argument specifies the maximum number of parallel read or write requests issued, defaulting to 128.
If progress_handler is specified, it will be called after each block of a file is successfully copied. The arguments passed to this handler will be the source path, destination path, bytes copied so far, and total bytes in the file being copied. If multiple source paths are provided or recurse is set to
True
, the progress_handler will be called consecutively on each file being copied.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 (
PurePath
,str
, orbytes
, or a sequence of these) – The paths of the remote files or directories to copydstpath (
PurePath
,str
, orbytes
) – (optional) The path of the remote file or directory to copy intopreserve (
bool
) – (optional) Whether or not to preserve the original file attributesrecurse (
bool
) – (optional) Whether or not to recursively copy directoriesfollow_symlinks (
bool
) – (optional) Whether or not to follow symbolic linksblock_size (
int
) – (optional) The block size to use for file reads and writesmax_requests (
int
) – (optional) The maximum number of parallel read or write requestsprogress_handler (
callable
) – (optional) The function to call to report copy progresserror_handler (
callable
) – (optional) The function to call when an error occurs
- Raises
- async mget(remotepaths, localpath=None, *, preserve=False, recurse=False, follow_symlinks=False, block_size=16384, max_requests=128, progress_handler=None, error_handler=None)[source]¶
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 wildcard patterns.
- async mput(localpaths, remotepath=None, *, preserve=False, recurse=False, follow_symlinks=False, block_size=16384, max_requests=128, progress_handler=None, error_handler=None)[source]¶
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 wildcard patterns.
- async mcopy(srcpaths, dstpath=None, *, preserve=False, recurse=False, follow_symlinks=False, block_size=16384, max_requests=128, progress_handler=None, error_handler=None)[source]¶
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 wildcard patterns.
File access methods
- open(path, mode='r', attrs=SFTPAttrs(), encoding='utf-8', errors='strict', block_size=SFTP_BLOCK_SIZE, max_requests=_MAX_SFTP_REQUESTS)[source]¶
Open a remote file
This method opens a remote file and returns an
SFTPClientFile
object which can be used to read and write data and get and set file attributes.The path can be either a
str
orbytes
value. If it is a str, it will be encoded using the file encoding specified when theSFTPClient
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.
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 toNone
, forcing all data to be read and written as bytes in binary format.Most applications should be able to use this method regardless of the version of the SFTP protocol negotiated with the SFTP server. A conversion from the pflags_or_mode values to the SFTPv5/v6 flag values will happen automatically. However, if an application wishes to set flags only available in SFTPv5/v6, the
open56()
method may be used to specify these flags explicitly.The attrs argument is used to set initial attributes of the file if it needs to be created. Otherwise, this argument is ignored.
The block_size argument specifies the size of parallel read and write requests issued on the file. If set to
None
, each read or write call will become a single request to the SFTP server. Otherwise, read or write calls larger than this size will be turned into parallel requests to the server of the requested size, defaulting to 16 KB.Note
The OpenSSH SFTP server will close the connection if it receives a message larger than 256 KB, and limits read requests to returning no more than 64 KB. So, when connecting to an OpenSSH SFTP server, it is recommended that the block_size be set below these sizes.
The max_requests argument specifies the maximum number of parallel read or write requests issued, defaulting to 128.
- Parameters
path (
PurePath
,str
, orbytes
) – The name of the remote file to openpflags_or_mode (
int
orstr
) – (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 createdencoding (
str
) – (optional) The Unicode encoding to use for data read and written to the remote fileerrors (
str
) – (optional) The error-handling mode if an invalid Unicode byte sequence is detected, defaulting to ‘strict’ which raises an exceptionblock_size (
int
orNone
) – (optional) The block size to use for read and write requestsmax_requests (
int
) – (optional) The maximum number of parallel read or write requests
- Returns
An
SFTPClientFile
to use to access the file- Raises
ValueError
if the mode is not validSFTPError
if the server returns an error
- open56(path, desired_access=ACE4_READ_DATA | ACE4_READ_ATTRIBUTES, flags=FXF_OPEN_EXISTING, attrs=SFTPAttrs(), encoding='utf-8', errors='strict', block_size=SFTP_BLOCK_SIZE, max_requests=_MAX_SFTP_REQUESTS)[source]¶
Open a remote file using SFTP v5/v6 flags
This method is very similar to
open()
, but the pflags_or_mode argument is replaced with SFTPv5/v6 desired_access and flags arguments. Most applications can continue to useopen()
even when talking to an SFTPv5/v6 server and the translation of the flags will happen automatically. However, if an application wishes to set flags only available in SFTPv5/v6, this method provides that capability.The following desired_access flags can be specified:
ACE4_READ_DATAACE4_WRITE_DATAACE4_APPEND_DATAACE4_READ_ATTRIBUTESACE4_WRITE_ATTRIBUTESThe following flags can be specified:
FXF_CREATE_NEWFXF_CREATE_TRUNCATEFXF_OPEN_EXISTINGFXF_OPEN_OR_CREATEFXF_TRUNCATE_EXISTINGFXF_APPEND_DATAFXF_APPEND_DATA_ATOMICFXF_BLOCK_READFXF_BLOCK_WRITEFXF_BLOCK_DELETEFXF_BLOCK_ADVISORY (SFTPv6)FXF_NOFOLLOW (SFTPv6)FXF_DELETE_ON_CLOSE (SFTPv6)FXF_ACCESS_AUDIT_ALARM_INFO (SFTPv6)FXF_ACCESS_BACKUP (SFTPv6)FXF_BACKUP_STREAM (SFTPv6)FXF_OVERRIDE_OWNER (SFTPv6)At this time, FXF_TEXT_MODE is not supported. Also, servers may support only a subset of these flags. For example, the AsyncSSH SFTP server doesn’t currently support ACLs, file locking, or most of the SFTPv6 open flags, but support for some of these may be added over time.
- Parameters
path (
PurePath
,str
, orbytes
) – The name of the remote file to opendesired_access (int) – (optional) The access mode to use for the remote file (see above)
flags (int) – (optional) The access flags to use for the remote file (see above)
attrs (
SFTPAttrs
) – (optional) File attributes to use if the file needs to be createdencoding (
str
) – (optional) The Unicode encoding to use for data read and written to the remote fileerrors (
str
) – (optional) The error-handling mode if an invalid Unicode byte sequence is detected, defaulting to ‘strict’ which raises an exceptionblock_size (
int
orNone
) – (optional) The block size to use for read and write requestsmax_requests (
int
) – (optional) The maximum number of parallel read or write requests
- Returns
An
SFTPClientFile
to use to access the file- Raises
ValueError
if the mode is not validSFTPError
if the server returns an error
- async rename(oldpath, newpath, flags=0)[source]¶
Rename a remote file, directory, or link
This method renames a remote file, directory, or link.
Note
By default, this version of rename will not overwrite the new path if it already exists. However, this can be controlled using the
flags
argument, available in SFTPv5 and later. When a connection is negotiated to use an earliler version of SFTP andflags
is set, this method will attempt to fall back to the OpenSSH “posix-rename” extension if it is available. That can also be invoked directly by callingposix_rename()
.- Parameters
oldpath (
PurePath
,str
, orbytes
) – The path of the remote file, directory, or link to renamenewpath (
PurePath
,str
, orbytes
) – The new name for this file, directory, or linkflags (
int
) – (optional) A combination of theFXR_OVERWRITE
,FXR_ATOMIC
, andFXR_NATIVE
flags to specify what happens whennewpath
already exists, defaulting to not allowing the overwrite (SFTPv5 and later)
- Raises
SFTPError
if the server returns an error
- async posix_rename(oldpath, newpath)[source]¶
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. If it is not available but the server supports SFTPv5 or later, this method will attempt to send the standard SFTP rename request with the
FXR_OVERWRITE
flag set.
- async symlink(oldpath, newpath)[source]¶
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.
- async realpath(path, *compose_paths, check=1)[source]¶
Return the canonical version of a remote path
This method returns a canonical version of the requested path.
- Parameters
path (
PurePath
,str
, orbytes
) – (optional) The path of the remote directory to canonicalizecompose_paths (
PurePath
,str
, orbytes
) – (optional) A list of additional paths that the server should compose withpath
before canonicalizing itcheck (int) – (optional) One of
FXRP_NO_CHECK
,FXRP_STAT_IF_EXISTS
, andFXRP_STAT_ALWAYS
, specifying when to perform a stat operation on the resulting path, defaulting toFXRP_NO_CHECK
- Returns
The canonical path as a
str
orbytes
, matching the type used to pass in the path ifcheck
is set toFXRP_NO_CHECK
, or anSFTPName
containing the canonical path name and attributes otherwise- Raises
SFTPError
if the server returns an error
File attribute access methods
- async setstat(path, attrs)[source]¶
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.
- async statvfs(path)[source]¶
Get attributes of a remote file system
This method queries the attributes of the file system containing the specified path.
- Parameters
path (
PurePath
,str
, orbytes
) – 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
- async chown(path, uid or owner, gid or group)[source]¶
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
- Raises
SFTPError
if the server returns an error
- async utime(path, times=None, ns=None)[source]¶
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 neither
times
nor ‘ns
is 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 (
PurePath
,str
, orbytes
) – The path of the remote file to changetimes (tuple of two
int
orfloat
values) – (optional) The new access and modify times, as seconds relative to the UNIX epochns (tuple of two
int
values) – (optional) The new access and modify times, as nanoseconds relative to the UNIX epoch
- Raises
SFTPError
if the server returns an error
Directory access methods
- async makedirs(path, attrs=SFTPAttrs())[source]¶
Create a remote directory with the specified attributes
This method creates a remote directory at the specified path similar to
mkdir()
, but it will also create any intermediate directories which don’t yet exist.If the target directory already exists and exist_ok is set to
False
, this method will raise an error.- Parameters
path (
PurePath
,str
, orbytes
) – The path of where the new remote directory should be createdattrs (
SFTPAttrs
) – (optional) The file attributes to use when creating the directory or any intermediate directoriesexist_ok (
bool
) – (optional) Whether or not to raise an error if thet target directory already exists
- Raises
SFTPError
if the server returns an error
- async rmtree(path, ignore_errors=False, onerror=None)[source]¶
Recursively delete a directory tree
This method removes all the files in a directory tree.
If ignore_errors is set, errors are ignored. Otherwise, if onerror is set, it will be called with arguments of the function which failed, the path it failed on, and exception information returns by
sys.exc_info()
.If follow_symlinks is set, files or directories pointed at by symlinks (and their subdirectories, if any) will be removed in addition to the links pointing at them.
- async scandir(path='.')[source]¶
Return names and attributes of the files in a remote directory
This method reads the contents of a directory, returning the names and attributes of what is contained there as an async iterator. If no path is provided, it defaults to the current remote working directory.
- async glob(patterns, error_handler=None)[source]¶
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.
Supported wildcard characters include ‘*’, ‘?’, and character ranges in square brackets. In addition, ‘**’ can be used to trigger a recursive directory search at that point in the pattern, and a trailing slash can be used to request that only directories get returned.
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.
Cleanup methods
SFTPClientFile¶
- class asyncssh.SFTPClientFile[source]¶
SFTP client remote file object
This class represents an open file on a remote SFTP server. It is opened with the
open()
method on theSFTPClient
class and provides methods to read and write data and get and set attributes on the open file.- async read(size=- 1, offset=None)[source]¶
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
str
orbytes
object is returned when at EOF.- Parameters
- Returns
- Raises
ValueError
if the file has been closedUnicodeDecodeError
if the data can’t be decoded using the requested encodingSFTPError
if the server returns an error
- async read_parallel(size=- 1, offset=None)[source]¶
Read parallel blocks of 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.
Data is returned as a series of tuples delivered by an async iterator, where each tuple contains an offset and data bytes. Encoding is ignored here, since multi-byte characters may be split across block boundaries.
To maximize performance, multiple reads are issued in parallel, and data blocks may be returned out of order. The size of the blocks and the maximum number of outstanding read requests can be controlled using the
block_size
andmax_requests
arguments passed in the call to theopen()
method on theSFTPClient
class.- Parameters
- Returns
an async iterator of tuples of offset and data bytes
- Raises
ValueError
if the file has been closedSFTPError
if the server returns an error
- async write(data, offset=None)[source]¶
Write data to the remote file
This method writes the specified data at the current position in the remote file.
- Parameters
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 closedUnicodeEncodeError
if the data can’t be encoded using the requested encodingSFTPError
if the server returns an error
- async seek(offset, from_what=SEEK_SET)[source]¶
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 iffrom_what
is set toSEEK_SET
(the default), relative to the current file position if it is set toSEEK_CUR
, or relative to the end of the file if it is set toSEEK_END
.- Parameters
offset (
int
) – The amount to seekfrom_what (
SEEK_SET
,SEEK_CUR
, orSEEK_END
) – (optional) The reference point to use
- Returns
The new byte offset from the beginning of the file
- async statvfs()[source]¶
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
- async utime(times=None, ns=None)[source]¶
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
- Raises
SFTPError
if the server returns an error
SFTPServer¶
- class asyncssh.SFTPServer(chan, chroot=None)[source]¶
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 operations to determine its result.
The
chan
object provided here is theSSHServerChannel
instance this SFTP server is associated with. It can be queried to determine which user the client authenticated as, environment variables set on the channel when it was opened, and key and certificate options or permissions associated with this session.Note
In AsyncSSH 1.x, this first argument was an
SSHServerConnection
, not anSSHServerChannel
. When moving to AsyncSSH 2.x, subclasses ofSFTPServer
which implement an __init__ method will need to be updated to account for this change, and pass this through to the parent.If the
chroot
argument is specified when this object is created, the defaultmap_path()
andreverse_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 therealpath()
andreadlink()
methods.SFTP server attributes
- channel¶
The channel associated with this SFTP server session
- connection¶
The channel associated with this SFTP server session
- env¶
The environment associated with this SFTP server session
This method returns the environment set by the client when this SFTP session was opened.
- Returns
A dictionary containing the environment variables set by the client
- logger¶
A logger associated with this SFTP server
Path remapping and display methods
- format_user(uid)[source]¶
Return the user name associated with a uid
This method returns a user name string to insert into the
longname
field of anSFTPName
object.By default, it calls the Python
pwd.getpwuid()
function if it is available, or returns the numeric uid as a string if not. If there is no uid, it returns an empty string.
- format_group(gid)[source]¶
Return the group name associated with a gid
This method returns a group name string to insert into the
longname
field of anSFTPName
object.By default, it calls the Python
grp.getgrgid()
function if it is available, or returns the numeric gid as a string if not. If there is no gid, it returns an empty string.
- format_longname(name)[source]¶
Format the long name associated with an SFTP name
This method fills in the
longname
field of aSFTPName
object. By default, it generates something similar to UNIX “ls -l” output. Thefilename
andattrs
fields of theSFTPName
should already be filled in before this method is called.
- map_path(path)[source]¶
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
bytes containing the local path name to operate on
- reverse_map_path(path)[source]¶
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
bytes containing the path name to report to the client
File access methods
- open(path, pflags, attrs)[source]¶
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.
- open56(path, desired_access, flags, attrs)[source]¶
Open a file to serve to a remote client (SFTPv5 and later)
This method returns a file object which can be used to read and write data and get and set file attributes.
Supported desired_access bits include
ACE4_READ_DATA
,ACE4_WRITE_DATA
,ACE4_APPEND_DATA
,ACE4_READ_ATTRIBUTES
, andACE4_WRITE_ATTRIBUTES
.Supported disposition bits in flags and their meanings are:
Disposition
Description
FXF_OPEN_EXISTING
Open an existing file
FXF_OPEN_OR_CREATE
Open an existing file or create a new one
FXF_CREATE_NEW
Create a new file
FXF_CREATE_TRUNCATE
Create a new file or truncate an existing one
FXF_TRUNCATE_EXISTING
Truncate an existing file
Other supported flag bits are:
Flag
Description
FXF_APPEND_DATA
Append data writes to the end of the file
The attrs argument is used to set initial attributes of the file if it needs to be created. Otherwise, this argument is ignored.
- Parameters
- Returns
A file object to use to access the file
- Raises
SFTPError
to return an error to the client
- rename(oldpath, newpath)[source]¶
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.
File attribute access methods
- setstat(path, attrs)[source]¶
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.
- statvfs(path)[source]¶
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)[source]¶
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
Cleanup methods
SFTPAttrs¶
- class asyncssh.SFTPAttrs[source]¶
SFTP file attributes
SFTPAttrs is a simple record class with the following fields:
Field
Description
Type
type
File type (SFTPv4+)
byte
size
File size in bytes
uint64
alloc_size
Allocation file size in bytes (SFTPv6+)
uint64
uid
User id of file owner
uint32
gid
Group id of file owner
uint32
owner
User name of file owner (SFTPv4+)
string
group
Group name of file owner (SFTPv4+)
string
permissions
Bit mask of POSIX file permissions
uint32
atime
Last access time, UNIX epoch seconds
uint64
atime_ns
Last access time, nanoseconds (SFTPv4+)
uint32
crtime
Creation time, UNIX epoch seconds (SFTPv4+)
uint64
crtime_ns
Creation time, nanoseconds (SFTPv4+)
uint32
mtime
Last modify time, UNIX epoch seconds
uint64
mtime_ns
Last modify time, nanoseconds (SFTPv4+)
uint32
ctime
Last change time, UNIX epoch seconds (SFTPv6+)
uint64
ctime_ns
Last change time, nanoseconds (SFTPv6+)
uint32
acl
Access control list for file (SFTPv4+)
bytes
attrib_bits
Attribute bits set for file (SFTPv5+)
uint32
attrib_valid
Valid attribute bits for file (SFTPv5+)
uint32
text_hint
Text/binary hint for file (SFTPv6+)
byte
mime_type
MIME type for file (SFTPv6+)
string
nlink
Link count for file (SFTPv6+)
uint32
untrans_name
Untranslated name for file (SFTPv6+)
bytes
Extended attributes can also be added via a field named
extended
which is a list of bytes 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[source]¶
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[source]¶
SFTP file name and attributes
SFTPName is a simple record class with the following fields:
A list of these is returned by
readdir()
inSFTPClient
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 and Ed448 keys are supported if OpenSSL 1.1.1b or later is installed. Alternately, Ed25519 support is available when the libnacl package and libsodium library are installed.
Supported certificate types include OpenSSH version 01 certificates for DSA, RSA, ECDSA, Ed25519, and Ed448 keys and X.509 certificates for DSA, RSA, and ECDSA keys.
Support is also available for the certificate critical options of force-command and source-address and the extensions permit-X11-forwarding, permit-agent-forwarding, permit-port-forwarding, and permit-pty in OpenSSH certificates.
Several public key and certificate formats are supported including PKCS#1 and PKCS#8 DER and PEM, OpenSSH, RFC4716, and X.509 DER and PEM 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 to read one or more private keys from.
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 corresponding certificate or certificate chain.
Key references can either be the name of a file to load a key from,
a byte string to import as a key, 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 a certificate
from, a byte string to import as a certificate, an already loaded
SSHCertificate
, or None
if no certificate should be
associated with the key.
Whenever a filename is provided to read the private key from, an attempt is made to load a corresponding certificate or certificate chain from a file constructed by appending ‘-cert.pub’ to the end of the name. X.509 certificates may also be provided in the same file as the private key, when using DER or PEM format.
When using X.509 certificates, a list of certificates can also be provided. These certificates should form a trust chain from a user or host certificate up to some self-signed root certificate authority which is trusted by the remote system.
Instead of passing tuples of keys and certificates or relying on file naming conventions for certificates, you also have the option of providing a list of keys and a separate list of certificates. In this case, AsyncSSH will automatically match up the keys with their associated certificates when they are present.
New private keys can be generated using the generate_private_key()
function. The resulting SSHKey
objects have methods which can
then be used to export the generated keys in several formats for
consumption by other tools, as well as methods for generating new
OpenSSH or X.509 certificates.
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 to read one or more public keys from.
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.
Specifying certificates¶
Certificates may be passed into AsyncSSH in a variety of forms. The simplest option is to pass the name of a file to read one or more certificates from.
An alternate form involves passing in a list of values each of which
can be either the name of a file to load a certificate from, a byte string
to import it from, or an already loaded SSHCertificate
object.
See the function import_certificate()
for the list of supported
certificate formats.
Specifying X.509 subject names¶
X.509 certificate subject names may be specified in place of public keys or certificates in authorized_keys and known_hosts files, allowing any X.509 certificate which matches that subject name to be considered a known host or authorized key. The syntax supported for this is compatible with PKIX-SSH, which adds X.509 certificate support to OpenSSH.
To specify a subject name pattern instead of a specific certificate, base64-encoded certificate data should be replaced with the string ‘Subject:’ followed by a comma-separated list of X.509 relative distinguished name components.
AsyncSSH extends the PKIX-SSH syntax to also support matching on a prefix of a subject name. To indicate this, a partial subject name can be specified which ends in ‘,*’. Any subject which matches the relative distinguished names listed before the “,*” will be treated as a match, even if the certificate provided has additional relative distinguished names following what was matched.
Specifying X.509 purposes¶
When performing X.509 certificate authentication, AsyncSSH can be passed in an allowed set of ExtendedKeyUsage purposes. Purposes are matched in X.509 certificates as OID values, but AsyncSSH also allows the following well-known purpose values to be specified by name:
Name |
OID |
---|---|
serverAuth |
1.3.6.1.5.5.7.3.1 |
clientAuth |
1.3.6.1.5.5.7.3.2 |
secureShellClient |
1.3.6.1.5.5.7.3.20 |
secureShellServer |
1.3.6.1.5.5.7.3.21 |
Values not in the list above can be specified directly by OID as a dotted numeric string value. Either a single value or a list of values can be provided.
The check succeeds if any of the specified values are present in the certificate’s ExtendedKeyUsage. It will also succeed if the certificate does not contain an ExtendedKeyUsage or if the ExtendedKeyUsage contains the OID 2.5.29.37.0, which indicates the certificate can be used for any purpose.
This check defaults to requiring a purpose of ‘secureShellCient’ for client certificates and ‘secureShellServer’ for server certificates and should not normally need to be changed. However, certificates which contain other purposes can be supported by providing alternate values to match against, or by passing in the purpose ‘any’ to disable this checking.
Specifying time values¶
When generating certificates, an optional validity interval can be
specified using the valid_after
and valid_before
parameters
to the generate_user_certificate()
and generate_host_certificate()
methods. These values can be specified in any of the following ways:
An int or float UNIX epoch time, such as what is returned by
time.time()
.A
datetime.datetime
value.A string value of
now
to request the current time.A string value in the form
YYYYMMDD
to specify an absolute date.A string value in the form
YYYYMMDDHHMMSS
to specify an absolute date and time.A time interval described in Specifying time intervals which is interpreted as a relative time from now. This value can be negative to refer to times in the past or positive to refer to times in the future.
SSHKey¶
- class asyncssh.SSHKey[source]¶
Parent class which holds an asymmetric encryption key
- get_comment(encoding='utf-8', errors='strict')[source]¶
Return the comment associated with this key as a Unicode string
- Parameters
- Returns
- Raises
UnicodeDecodeError
if the comment cannot be decoded using the specified encoding
- set_comment(comment, encoding='utf-8', errors='strict')[source]¶
Set the comment associated with this key
- Parameters
- Raises
UnicodeEncodeError
if the comment cannot be encoded using the specified encoding
- get_fingerprint(hash_name='sha256')[source]¶
Get the fingerprint of this key
Available hashes include:
md5, sha1, sha256, sha384, sha512
- Parameters
hash_name (
str
) – (optional) The hash algorithm to use to construct the fingerprint.- Returns
- Raises
ValueError
if the hash name is invalid
- generate_user_certificate(user_key, key_id, version=1, serial=0, principals=(), valid_after=0, valid_before=18446744073709551615, force_command=None, source_address=None, permit_x11_forwarding=True, permit_agent_forwarding=True, permit_port_forwarding=True, permit_pty=True, permit_user_rc=True, touch_required=True, sig_alg=(), comment=())[source]¶
Generate a new SSH user certificate
This method returns an SSH user certificate with the requested attributes signed by this private key.
- Parameters
user_key (
SSHKey
) – The user’s public key.key_id (
str
) – The key identifier associated with this certificate.version (
int
) – (optional) The version of certificate to create, defaulting to 1.serial (
int
) – (optional) The serial number of the certificate, defaulting to 0.principals (
str
orlist
ofstr
) – (optional) The user names this certificate is valid for. By default, it can be used with any user name.valid_after – (optional) The earliest time the certificate is valid for, defaulting to no restriction on when the certificate starts being valid. See Specifying time values for allowed time specifications.
valid_before – (optional) The latest time the certificate is valid for, defaulting to no restriction on when the certificate stops being valid. See Specifying time values for allowed time specifications.
force_command (
str
orNone
) – (optional) The command (if any) to force a session to run when this certificate is used.source_address (list of ip_address and ip_network values) – (optional) A list of source addresses and networks for which the certificate is valid, defaulting to all addresses.
permit_x11_forwarding (
bool
) – (optional) Whether or not to allow this user to use X11 forwarding, defaulting toTrue
.permit_agent_forwarding (
bool
) – (optional) Whether or not to allow this user to use agent forwarding, defaulting toTrue
.permit_port_forwarding (
bool
) – (optional) Whether or not to allow this user to use port forwarding, defaulting toTrue
.permit_pty (
bool
) – (optional) Whether or not to allow this user to allocate a pseudo-terminal, defaulting toTrue
.permit_user_rc (
bool
) – (optional) Whether or not to run the user rc file when this certificate is used, defaulting toTrue
.touch_required (
bool
) – (optional) Whether or not to require the user to touch the security key when authenticating with it, defaulting toTrue
.sig_alg (
str
) – (optional) The algorithm to use when signing the new certificate.comment (
str
,bytes
, orNone
) – The comment to associate with this certificate. By default, the comment will be set to the comment currently set on user_key.
- Returns
- Raises
ValueError
if the validity times are invalidKeyGenerationError
if the requested certificate parameters are unsupported
- generate_host_certificate(host_key, key_id, version=1, serial=0, principals=(), valid_after=0, valid_before=18446744073709551615, sig_alg=(), comment=())[source]¶
Generate a new SSH host certificate
This method returns an SSH host certificate with the requested attributes signed by this private key.
- Parameters
host_key (
SSHKey
) – The host’s public key.key_id (
str
) – The key identifier associated with this certificate.version (
int
) – (optional) The version of certificate to create, defaulting to 1.serial (
int
) – (optional) The serial number of the certificate, defaulting to 0.principals (
str
orlist
ofstr
) – (optional) The host names this certificate is valid for. By default, it can be used with any host name.valid_after – (optional) The earliest time the certificate is valid for, defaulting to no restriction on when the certificate starts being valid. See Specifying time values for allowed time specifications.
valid_before – (optional) The latest time the certificate is valid for, defaulting to no restriction on when the certificate stops being valid. See Specifying time values for allowed time specifications.
sig_alg (
str
) – (optional) The algorithm to use when signing the new certificate.comment (
str
,bytes
, orNone
) – The comment to associate with this certificate. By default, the comment will be set to the comment currently set on host_key.
- Returns
- Raises
ValueError
if the validity times are invalidKeyGenerationError
if the requested certificate parameters are unsupported
- generate_x509_user_certificate(user_key, subject, issuer=None, serial=None, principals=(), valid_after=0, valid_before=18446744073709551615, purposes='secureShellClient', hash_alg=(), comment=())[source]¶
Generate a new X.509 user certificate
This method returns an X.509 user certificate with the requested attributes signed by this private key.
- Parameters
user_key (
SSHKey
) – The user’s public key.subject (
str
) – The subject name in the certificate, expresed as a comma-separated list of X.509name=value
pairs.issuer (
str
) – (optional) The issuer name in the certificate, expresed as a comma-separated list of X.509name=value
pairs. If not specified, the subject name will be used, creating a self-signed certificate.serial (
int
) – (optional) The serial number of the certificate, defaulting to a random 64-bit value.principals (
str
orlist
ofstr
) – (optional) The user names this certificate is valid for. By default, it can be used with any user name.valid_after – (optional) The earliest time the certificate is valid for, defaulting to no restriction on when the certificate starts being valid. See Specifying time values for allowed time specifications.
valid_before – (optional) The latest time the certificate is valid for, defaulting to no restriction on when the certificate stops being valid. See Specifying time values for allowed time specifications.
purposes (
str
,list
ofstr
, orNone
) – (optional) The allowed purposes for this certificate orNone
to not restrict the certificate’s purpose, defaulting to ‘secureShellClient’hash_alg (
str
) – (optional) The hash algorithm to use when signing the new certificate, defaulting to SHA256.comment (
str
,bytes
, orNone
) – (optional) The comment to associate with this certificate. By default, the comment will be set to the comment currently set on user_key.
- Returns
- Raises
ValueError
if the validity times are invalidKeyGenerationError
if the requested certificate parameters are unsupported
- generate_x509_host_certificate(host_key, subject, issuer=None, serial=None, principals=(), valid_after=0, valid_before=18446744073709551615, purposes='secureShellServer', hash_alg=(), comment=())[source]¶
Generate a new X.509 host certificate
This method returns an X.509 host certificate with the requested attributes signed by this private key.
- Parameters
host_key (
SSHKey
) – The host’s public key.subject (
str
) – The subject name in the certificate, expresed as a comma-separated list of X.509name=value
pairs.issuer (
str
) – (optional) The issuer name in the certificate, expresed as a comma-separated list of X.509name=value
pairs. If not specified, the subject name will be used, creating a self-signed certificate.serial (
int
) – (optional) The serial number of the certificate, defaulting to a random 64-bit value.principals (
str
orlist
ofstr
) – (optional) The host names this certificate is valid for. By default, it can be used with any host name.valid_after – (optional) The earliest time the certificate is valid for, defaulting to no restriction on when the certificate starts being valid. See Specifying time values for allowed time specifications.
valid_before – (optional) The latest time the certificate is valid for, defaulting to no restriction on when the certificate stops being valid. See Specifying time values for allowed time specifications.
purposes (
str
,list
ofstr
, orNone
) – (optional) The allowed purposes for this certificate orNone
to not restrict the certificate’s purpose, defaulting to ‘secureShellServer’hash_alg (
str
) – (optional) The hash algorithm to use when signing the new certificate, defaulting to SHA256.comment (
str
,bytes
, orNone
) – (optional) The comment to associate with this certificate. By default, the comment will be set to the comment currently set on host_key.
- Returns
- Raises
ValueError
if the validity times are invalidKeyGenerationError
if the requested certificate parameters are unsupported
- generate_x509_ca_certificate(ca_key, subject, issuer=None, serial=None, valid_after=0, valid_before=18446744073709551615, ca_path_len=None, hash_alg=(), comment=())[source]¶
Generate a new X.509 CA certificate
This method returns an X.509 CA certificate with the requested attributes signed by this private key.
- Parameters
ca_key (
SSHKey
) – The new CA’s public key.subject (
str
) – The subject name in the certificate, expresed as a comma-separated list of X.509name=value
pairs.issuer (
str
) – (optional) The issuer name in the certificate, expresed as a comma-separated list of X.509name=value
pairs. If not specified, the subject name will be used, creating a self-signed certificate.serial (
int
) – (optional) The serial number of the certificate, defaulting to a random 64-bit value.valid_after – (optional) The earliest time the certificate is valid for, defaulting to no restriction on when the certificate starts being valid. See Specifying time values for allowed time specifications.
valid_before – (optional) The latest time the certificate is valid for, defaulting to no restriction on when the certificate stops being valid. See Specifying time values for allowed time specifications.
ca_path_len (
int
orNone
) – (optional) The maximum number of levels of intermediate CAs allowed below this new CA orNone
to not enforce a limit, defaulting to no limit.hash_alg (
str
) – (optional) The hash algorithm to use when signing the new certificate, defaulting to SHA256.comment (
str
,bytes
, orNone
) – (optional) The comment to associate with this certificate. By default, the comment will be set to the comment currently set on ca_key.
- Returns
- Raises
ValueError
if the validity times are invalidKeyGenerationError
if the requested certificate parameters are unsupported
- export_private_key(format_name='openssh', passphrase=None, cipher_name='aes256-cbc', hash_name='sha256', pbe_version=2, rounds=128, ignore_few_rounds=False)[source]¶
Export a private key in the requested format
This method 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
By default, openssh format will be used.
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
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 128.
Note
The openssh format uses bcrypt for encryption, but unlike the traditional bcrypt cost factor used in password hashing which scales logarithmically, the encryption strength here scales linearly with the rounds value. Since the cipher is rekeyed 64 times per round, the default rounds value of 128 corresponds to 8192 total iterations, which is the equivalent of a bcrypt cost factor of 13.
- Parameters
format_name (
str
) – (optional) The format to export the key in.passphrase (
str
orbytes
) – (optional) A passphrase to encrypt the private key with.cipher_name (
str
) – (optional) The cipher to use for private key encryption.hash_name (
str
) – (optional) The hash to use for private key encryption.pbe_version (
int
) – (optional) The PBE version to use for private key encryption.rounds (
int
) – (optional) The number of KDF rounds to apply to the passphrase.
- Returns
bytes
representing the exported private key
- export_public_key(format_name='openssh')[source]¶
Export a public key in the requested format
This method returns this object’s public key encoded in the requested format. Available formats include:
pkcs1-der, pkcs1-pem, pkcs8-der, pkcs8-pem, openssh, rfc4716
By default, openssh format will be used.
- write_private_key(filename, *args, **kwargs)[source]¶
Write a private key to a file in the requested format
This method is a simple wrapper around
export_private_key()
which writes the exported key data to a file.- Parameters
filename (
PurePath
orstr
) – 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)[source]¶
Write a public key to a file in the requested format
This method is a simple wrapper around
export_public_key()
which writes the exported key data to a file.- Parameters
filename (
PurePath
orstr
) – The filename to write the public key to.*args,**kwargs – Additional arguments to pass through to
export_public_key()
.
- append_private_key(filename, *args, **kwargs)[source]¶
Append a private key to a file in the requested format
This method is a simple wrapper around
export_private_key()
which appends the exported key data to an existing file.- Parameters
filename (
PurePath
orstr
) – The filename to append the private key to.*args,**kwargs – Additional arguments to pass through to
export_private_key()
.
- append_public_key(filename, *args, **kwargs)[source]¶
Append a public key to a file in the requested format
This method is a simple wrapper around
export_public_key()
which appends the exported key data to an existing file.- Parameters
filename (
PurePath
orstr
) – The filename to append the public key to.*args,**kwargs – Additional arguments to pass through to
export_public_key()
.
SSHKeyPair¶
- class asyncssh.SSHKeyPair[source]¶
Parent class which represents an asymmetric key pair
This is an abstract class which provides a method to sign data with a private key and members to access the corresponding algorithm and public key or certificate information needed to identify what key was used for signing.
- get_comment(encoding='utf-8', errors='strict')[source]¶
Return the comment associated with this key pair as a Unicode string
- Parameters
- Returns
- Raises
UnicodeDecodeError
if the comment cannot be decoded using the specified encoding
- set_comment(comment, encoding='utf-8', errors='strict')[source]¶
Set the comment associated with this key pair
- Parameters
- Raises
UnicodeEncodeError
if the comment cannot be encoded using the specified encoding
SSHCertificate¶
- class asyncssh.SSHCertificate[source]¶
Parent class which holds an SSH certificate
- get_comment(encoding='utf-8', errors='strict')[source]¶
Return the comment associated with this certificate as a Unicode string
- Parameters
- Returns
- Raises
UnicodeDecodeError
if the comment cannot be decoded using the specified encoding
- set_comment(comment, encoding='utf-8', errors='strict')[source]¶
Set the comment associated with this certificate
- Parameters
- Raises
UnicodeEncodeError
if the comment cannot be encoded using the specified encoding
generate_private_key¶
- asyncssh.generate_private_key(alg_name, comment=None, **kwargs)[source]¶
Generate a new private key
This function generates a new private key of a type matching the requested SSH algorithm. Depending on the algorithm, additional parameters can be passed which affect the generated key.
Available algorithms include:
ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, ecdsa-sha2-nistp521, ecdsa-sha2-1.3.132.0.10, ssh-ed25519, ssh-ed448, sk-ecdsa-sha2-nistp256@openssh.com, sk-ssh-ed25519@openssh.com
For dss keys, no parameters are supported. The key size is fixed at 1024 bits due to the use of SHA1 signatures.
For rsa keys, the key size can be specified using the
key_size
parameter, and the RSA public exponent can be changed using theexponent
parameter. By default, generated keys are 2048 bits with a public exponent of 65537.For ecdsa keys, the curve to use is part of the SSH algorithm name and that determines the key size. No other parameters are supported.
For ed25519 and ed448 keys, no parameters are supported. The key size is fixed by the algorithms at 256 bits and 448 bits, respectively.
For sk keys, the application name to associate with the generated key can be specified using the
application
parameter. It defaults to'ssh:'
. The user name to associate with the generated key can be specified using theuser
parameter. It defaults to'AsyncSSH'
.When generating an sk key, a PIN can be provided via the
pin
parameter if the security key requires it.The
resident
parameter can be set toTrue
to request that a resident key be created on the security key. This allows the key handle and public key information to later be retrieved so that the generated key can be used without having to store any information on the client system. It defaults toFalse
.You can enable or disable the security key touch requirement by setting the
touch_required
parameter. It defaults toTrue
, requiring that the user confirm their presence by touching the security key each time they use it to authenticate.- Parameters
alg_name (
str
) – The SSH algorithm name corresponding to the desired type of key.comment (
str
,bytes
, orNone
) – (optional) A comment to associate with this key.key_size (
int
) – (optional) The key size in bits for RSA keys.exponent (
int
) – (optional) The public exponent for RSA keys.application (
str
) – (optional) The application name to associate with the generated SK key, defaulting to'ssh:'
.user (
str
) – (optional) The user name to associate with the generated SK key, defaulting to'AsyncSSH'
.pin (
str
) – (optional) The PIN to use to access the security key, defaulting toNone
.resident (
bool
) – (optional) Whether or not to create a resident key on the security key, defaulting toFalse
.touch_required (
bool
) – (optional) Whether or not to require the user to touch the security key when authenticating with it, defaulting toTrue
.
- Returns
An
SSHKey
private key- Raises
KeyGenerationError
if the requested key parameters are unsupported
import_private_key¶
- asyncssh.import_private_key(data, passphrase=None, unsafe_skip_rsa_key_validation=None)[source]¶
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
passphrase (
str
orbytes
) – (optional) The passphrase to use to decrypt the key.unsafe_skip_rsa_key_validation (bool) – (optional) Whether or not to skip key validation when loading RSA private keys, defaulting to performing these checks unless changed by calling
set_default_skip_rsa_key_validation()
.
- Returns
An
SSHKey
private key
import_public_key¶
import_certificate¶
- asyncssh.import_certificate(data)[source]¶
Import a certificate
This function imports an SSH certificate in DER, PEM, OpenSSH, or RFC4716 format.
- Parameters
- Returns
An
SSHCertificate
object
read_private_key¶
- asyncssh.read_private_key(filename, passphrase=None, unsafe_skip_rsa_key_validation=None)[source]¶
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
passphrase (
str
orbytes
) – (optional) The passphrase to use to decrypt the key.unsafe_skip_rsa_key_validation (bool) – (optional) Whether or not to skip key validation when loading RSA private keys, defaulting to performing these checks unless changed by calling
set_default_skip_rsa_key_validation()
.
- Returns
An
SSHKey
private key
read_public_key¶
- asyncssh.read_public_key(filename)[source]¶
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.
read_certificate¶
- asyncssh.read_certificate(filename)[source]¶
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 (
PurePath
orstr
) – The file to read the certificate from.- Returns
An
SSHCertificate
object
read_private_key_list¶
- asyncssh.read_private_key_list(filename, passphrase=None, unsafe_skip_rsa_key_validation=None)[source]¶
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 (
PurePath
orstr
) – The file to read the keys from.passphrase (
str
orbytes
) – (optional) The passphrase to use to decrypt the keys.unsafe_skip_rsa_key_validation (bool) – (optional) Whether or not to skip key validation when loading RSA private keys, defaulting to performing these checks unless changed by calling
set_default_skip_rsa_key_validation()
.
- Returns
A list of
SSHKey
private keys
read_public_key_list¶
- asyncssh.read_public_key_list(filename)[source]¶
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.
read_certificate_list¶
- asyncssh.read_certificate_list(filename)[source]¶
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 (
PurePath
orstr
) – The file to read the certificates from.- Returns
A list of
SSHCertificate
certificates
load_keypairs¶
- asyncssh.load_keypairs(keylist, passphrase=None, certlist=(), skip_public=False, ignore_encrypted=False, unsafe_skip_rsa_key_validation=None)[source]¶
Load SSH private keys and optional matching certificates
This function loads a list of SSH keys and optional matching certificates.
When certificates are specified, the private key is added to the list both with and without the certificate.
- Parameters
keylist (see Specifying private keys) – The list of private keys and certificates to load.
passphrase (
str
orbytes
) – (optional) The passphrase to use to decrypt private keys.certlist (see Specifying certificates) – (optional) A list of certificates to attempt to pair with the provided list of private keys.
skip_public (
bool
) – (optional) An internal parameter used to skip public keys and certificates when IdentitiesOnly and IdentityFile are used to specify a mixture of private and public keys.unsafe_skip_rsa_key_validation (bool) – (optional) Whether or not to skip key validation when loading RSA private keys, defaulting to performing these checks unless changed by calling
set_default_skip_rsa_key_validation()
.
- Returns
A list of
SSHKeyPair
objects
load_public_keys¶
- asyncssh.load_public_keys(keylist)[source]¶
Load public keys
This function loads a list of SSH public keys.
- Parameters
keylist (see Specifying public keys) – The list of public keys to load.
- Returns
A list of
SSHKey
objects
load_certificates¶
- asyncssh.load_certificates(certlist)[source]¶
Load certificates
This function loads a list of OpenSSH or X.509 certificates.
- Parameters
certlist (see Specifying certificates) – The list of certificates to load.
- Returns
A list of
SSHCertificate
objects
load_pkcs11_keys¶
load_resident_keys¶
- asyncssh.load_resident_keys(pin, *, application='ssh:', user=None, touch_required=True)[source]¶
Load keys resident on attached FIDO2 security keys
This function loads keys resident on any FIDO2 security keys currently attached to the system. The user name associated with each key is returned in the key’s comment field.
- Parameters
pin (
str
) – The PIN to use to access the security keys, defaulting toNone
.application (
str
) – (optional) The application name associated with the keys to load, defaulting to'ssh:'
.user (
str
) – (optional) The user name associated with the keys to load. By default, keys for all users are loaded.touch_required (
bool
) – (optional) Whether or not to require the user to touch the security key when authenticating with it, defaulting toTrue
.
set_default_skip_rsa_key_validation¶
- asyncssh.set_default_skip_rsa_key_validation(skip_validation)[source]¶
Set whether to disable RSA key validation in OpenSSL
OpenSSL 3.x does additional validation when loading RSA keys as an added security measure. However, the result is that loading a key can take significantly longer than it did before.
If all your RSA keys are coming from a trusted source, you can call this function with a value of
True
to default to skipping these checks on RSA keys, reducing the cost back down to what it was in earlier releases.This can also be set on a case by case basis by using the new
unsafe_skip_rsa_key_validation
argument on the functions used to load keys. This will only affect loading keys of type RSA.Note
The extra cost only applies to loading existing keys, and not to generating new keys. Also, in cases where a key is used repeatedly, it can be loaded once into an
SSHKey
object and reused without having to pay the cost each time. So, this call should not be needed in most applications.If an application does need this, it is strongly recommended that the
unsafe_skip_rsa_key_validation
argument be used rather than using this function to change the default behavior for all load operations.
SSH Agent Support¶
AsyncSSH supports the ability to use private keys managed by the OpenSSH
ssh-agent on UNIX systems. It can connect via a UNIX domain socket to
the agent and offload all private key operations to it, avoiding the need
to read these keys into AsyncSSH itself. An ssh-agent is automatically
used in create_connection()
when a valid SSH_AUTH_SOCK
is set
in the environment. An alternate path to the agent can be specified via
the agent_path
argument to this function.
An ssh-agent can also be accessed directly from AsyncSSH by calling
connect_agent()
. When successful, this function returns an
SSHAgentClient
which can be used to get a list of available
keys, add and remove keys, and lock and unlock access to this agent.
SSH agent forwarding may be enabled when making outbound SSH connections
by specifying the agent_forwarding
argument when calling
create_connection()
, allowing processes running on the server
to tunnel requests back over the SSH connection to the client’s ssh-agent.
Agent forwarding can be enabled when starting an SSH server by
specifying the agent_forwarding
argument when calling
create_server()
. In this case, the client’s ssh-agent can be
accessed from the server by passing the SSHServerConnection
as
the argument to connect_agent()
instead of a local path. Alternately,
when an SSHServerChannel
has been opened, the get_agent_path()
method may be called on it to get a
path to a UNIX domain socket which can be passed as the SSH_AUTH_SOCK
to local applications which need this access. Any requests sent to this
socket are forwarded over the SSH connection to the client’s ssh-agent.
SSHAgentClient¶
- class asyncssh.SSHAgentClient[source]¶
SSH agent client
- async get_keys(identities=None)[source]¶
Request the available client keys
This method is a coroutine which returns a list of client keys available in the ssh-agent.
- Parameters
identities – (optional) A list of allowed byte string identities to return. If empty, all identities on the SSH agent will be returned.
- Returns
A list of
SSHKeyPair
objects
- async add_keys(keylist=(), passphrase=None, lifetime=None, confirm=False)[source]¶
Add keys to the agent
This method adds a list of local private keys and optional matching certificates to the agent.
- Parameters
keylist (see Specifying private keys) – (optional) The list of keys to add. If not specified, an attempt will be made to load keys from the files
.ssh/id_ed25519_sk
,.ssh/id_ecdsa_sk
,.ssh/id_ed448
,.ssh/id_ed25519
,.ssh/id_ecdsa
,.ssh/id_rsa
and.ssh/id_dsa
in the user’s home directory with optional matching certificates loaded from the files.ssh/id_ed25519_sk-cert.pub
,.ssh/id_ecdsa_sk-cert.pub
,.ssh/id_ed448-cert.pub
,.ssh/id_ed25519-cert.pub
,.ssh/id_ecdsa-cert.pub
,.ssh/id_rsa-cert.pub
, and.ssh/id_dsa-cert.pub
. Failures when adding keys are ignored in this case, as the agent may not recognize some of these key types.passphrase (
str
) – (optional) The passphrase to use to decrypt the keys.lifetime (
int
orNone
) – (optional) The time in seconds after which the keys should be automatically deleted, orNone
to store these keys indefinitely (the default).confirm (
bool
) – (optional) Whether or not to require confirmation for each private key operation which uses these keys, defaulting toFalse
.
- Raises
ValueError
if the keys cannot be added
- async add_smartcard_keys(provider, pin=None, lifetime=None, confirm=False)[source]¶
Store keys associated with a smart card in the agent
- Parameters
provider (
str
) – The name of the smart card providerpin (
str
orNone
) – (optional) The PIN to use to unlock the smart cardlifetime (
int
orNone
) – (optional) The time in seconds after which the keys should be automatically deleted, orNone
to store these keys indefinitely (the default).confirm (
bool
) – (optional) Whether or not to require confirmation for each private key operation which uses these keys, defaulting toFalse
.
- Raises
ValueError
if the keys cannot be added
- async remove_keys(keylist)[source]¶
Remove a key stored in the agent
- Parameters
keylist (
list
ofSSHKeyPair
) – The list of keys to remove.- Raises
ValueError
if any keys are not found
- async remove_all()[source]¶
Remove all keys stored in the agent
- Raises
ValueError
if the keys can’t be removed
- async lock(passphrase)[source]¶
Lock the agent using the specified passphrase
Note
The lock and unlock actions don’t appear to be supported on the Windows 10 OpenSSH agent.
- Parameters
passphrase (
str
) – The passphrase required to later unlock the agent- Raises
ValueError
if the agent can’t be locked
- async unlock(passphrase)[source]¶
Unlock the agent using the specified passphrase
Note
The lock and unlock actions don’t appear to be supported on the Windows 10 OpenSSH agent.
- Parameters
passphrase (
str
) – The passphrase to use to unlock the agent- Raises
ValueError
if the agent can’t be unlocked
- close()[source]¶
Close the SSH agent connection
This method closes the connection to the ssh-agent. Any attempts to use this
SSHAgentClient
or the key pairs it previously returned will result in an error.
SSHAgentKeyPair¶
- class asyncssh.SSHAgentKeyPair[source]¶
Surrogate for a key managed by the SSH agent
- get_key_type()¶
Return what type of key pair this is
This method returns ‘local’ for locally loaded keys, and ‘agent’ for keys managed by an SSH agent.
- get_algorithm()¶
Return the algorithm associated with this key pair
- get_comment(encoding='utf-8', errors='strict')¶
Return the comment associated with this key pair as a Unicode string
- Parameters
- Returns
- Raises
UnicodeDecodeError
if the comment cannot be decoded using the specified encoding
- set_comment(comment, encoding='utf-8', errors='strict')¶
Set the comment associated with this key pair
- Parameters
- Raises
UnicodeEncodeError
if the comment cannot be encoded using the specified encoding
connect_agent¶
- asyncssh.connect_agent(agent_path='')[source]¶
Make a connection to the SSH agent
This function attempts to connect to an ssh-agent process listening on a UNIX domain socket at
agent_path
. If not provided, it will attempt to get the path from theSSH_AUTH_SOCK
environment variable.If the connection is successful, an
SSHAgentClient
object is returned that has methods on it you can use to query the ssh-agent. If no path is specified and the environment variable is not set or the connection to the agent fails, an error is raised.- Parameters
agent_path (
str
orSSHServerConnection
) – (optional) The path to use to contact the ssh-agent process, or theSSHServerConnection
to forward the agent request over.- Returns
- Raises
OSError
orChannelOpenError
if the connection to the agent can’t be opened
Config File Support¶
AsyncSSH has partial support for parsing OpenSSH client and server configuration files (documented in the “ssh_config” and “sshd_config” UNIX man pages, respectively). Not all OpenSSH configuration options are applicable, so unsupported options are simply ignored. See below for the OpenSSH config options that AsyncSSH supports.
AsyncSSH also supports “Host” and “Match” conditional blocks. As with the config options themselves, not all match criteria are supported, but the supported criteria should function similar to OpenSSH.
AsyncSSH also supports the “Include” directive, to allow one config file trigger the loading of others.
Supported client config options¶
The following OpenSSH client config options are currently supported:
AddressFamilyBindAddressCASignatureAlgorithmsCertificateFileChallengeResponseAuthenticationCiphersCompressionConnectTimeoutEnableSSHKeySignForwardAgentForwardX11TrustedGlobalKnownHostsFileGSSAPIAuthenticationGSSAPIDelegateCredentialsGSSAPIKeyExchangeHostbasedAuthenticationHostKeyAlgorithmsHostKeyAliasHostnameIdentityAgentIdentityFileKbdInteractiveAuthenticationKexAlgorithmsMACsPasswordAuthenticationPreferredAuthenticationsPortProxyCommandProxyJumpPubkeyAuthenticationRekeyLimitRemoteCommandRequestTTYSendEnvServerAliveCountMaxServerAliveIntervalSetEnvTCPKeepAliveUserUserKnownHostsFile
For the “Match” conditional, the following criteria are currently supported:
AllExecHostLocalUserOriginalHostUserWarning
When instantiating
SSHClientConnectionOptions
objects manually within an asyncio task, you may block the event loop if the options refer to a config file with “Match Exec” directives which don’t return immediate results. In such cases, the asynciorun_in_executor()
function should be used. This is taken care of automatically when options objects are created by AsyncSSH APIs such asconnect()
andlisten()
.
The following client config token expansions are currently supported:
Token |
Expansion |
---|---|
%% |
Literal ‘%’ |
%C |
SHA-1 Hash of connection info (local host, host, port, user) |
%d |
Local user’s home directory |
%h |
Remote host |
%i |
Local uid (UNIX-only) |
%L |
Short local hostname (without the domain) |
%l |
Local hostname (including the domain) |
%n |
Original remote host |
%p |
Remote port |
%r |
Remote username |
%u |
Local username |
These expansions are available in the values of the following config options:
CertificateFileIdentityAgentIdentityFileRemoteCommand
Supported server config options¶
The following OpenSSH server config options are currently supported:
AddressFamilyAuthorizedKeysFileAllowAgentForwardingBindAddressCASignatureAlgorithmsChallengeResponseAuthenticationCiphersClientAliveCountMaxClientAliveIntervalCompressionGSSAPIAuthenticationGSSAPIKeyExchangeHostbasedAuthenticationHostCertificateHostKeyKbdInteractiveAuthenticationKexAlgorithmsLoginGraceTimeMACsPasswordAuthenticationPermitTTYPortProxyCommandPubkeyAuthenticationRekeyLimitTCPKeepAliveUseDNS
For the “Match” conditional, the following criteria are currently supported:
AllExecAddressHostLocalAddressLocalPortUserWarning
When instantiating
SSHServerConnectionOptions
objects manually within an asyncio task, you may block the event loop if the options refer to a config file with “Match Exec” directives which don’t return immediate results. In such cases, the asynciorun_in_executor()
function should be used. This is taken care of automatically when options objects are created by AsyncSSH APIs such asconnect()
andlisten()
.
The following server config token expansions are currently supported:
Token |
Expansion |
---|---|
%% |
Literal ‘%’ |
%u |
Username |
These expansions are available in the values of the following config options:
AuthorizedKeysFile
Specifying byte counts¶
A byte count may be passed into AsyncSSH as an integer value, or as a string made up of a mix of numbers followed by an optional letter of ‘k’, ‘m’, or ‘g’, indicating kilobytes, megabytes, or gigabytes, respectively. Multiple of these values can be included. For instance, ‘2.5m’ means 2.5 megabytes. This could also be expressed as ‘2m512k’ or ‘2560k’.
Specifying time intervals¶
A time interval may be passed into AsyncSSH as an integer or float value, or as a string made up of a mix of positive or negative numbers and the letters ‘w’, ‘d’, ‘h’, ‘m’, and ‘s’, indicating weeks, days, hours, minutes, or seconds, respectively. Multiple of these values can be included. For instance, ‘1w2d3h’ means 1 week, 2 days, and 3 hours.
Known Hosts¶
AsyncSSH supports OpenSSH-style known_hosts files, including both
plain and hashed host entries. Regular and negated host patterns are
supported in plain entries. AsyncSSH also supports the @cert_authority
marker to indicate keys and certificates which should be trusted as
certificate authorities and the @revoked
marker to indicate keys and
certificates which should be explicitly reported as no longer trusted.
Specifying known hosts¶
Known hosts may be passed into AsyncSSH via the known_hosts
argument
to create_connection()
. This can be the name of a file or list of files
containing known hosts, a byte string containing data in known hosts format,
or an SSHKnownHosts
object which was previously imported from a
string by calling import_known_hosts()
or read from files by calling
read_known_hosts()
. In all of these cases, the host patterns in the
list will be compared against the target host, address, and port being
connected to and the matching trusted host keys, trusted CA keys, revoked
keys, trusted X.509 certificates, revoked X.509 certificates, trusted
X.509 subject names, and revoked X.509 subject names will be returned.
Alternately, a function can be passed in as the known_hosts
argument
that accepts a target host, address, and port and returns lists containing
trusted host keys, trusted CA keys, revoked keys, trusted X.509 certificates,
revoked X.509 certificates, trusted X.509 subject names, and revoked X.509
subject names.
If no matching is required and the caller already knows exactly what the
above values should be, these seven lists can also be provided directly in
the known_hosts
argument.
See Specifying public keys for the allowed form of public key values which can be provided, Specifying certificates for the allowed form of certificates, and Specifying X.509 subject names for the allowed form of X.509 subject names.
SSHKnownHosts¶
import_known_hosts¶
- asyncssh.import_known_hosts(data)[source]¶
Import SSH known hosts
This function imports known host patterns and keys in OpenSSH known hosts format.
- Parameters
data (
str
) – The known hosts data to import- Returns
An
SSHKnownHosts
object
read_known_hosts¶
- asyncssh.read_known_hosts(filelist)[source]¶
Read SSH known hosts from a file or list of files
This function reads known host patterns and keys in OpenSSH known hosts format from a file or list of files.
- Parameters
filelist (
str
orlist
ofstr
) – The file or list of files to read the known hosts from- Returns
An
SSHKnownHosts
object
match_known_hosts¶
- asyncssh.match_known_hosts(known_hosts, host, addr, port)[source]¶
Match a host, IP address, and port against a known_hosts list
This function looks up a host, IP address, and port in a list of host patterns in OpenSSH
known_hosts
format and returns the host keys, CA keys, and revoked keys which match.The
known_hosts
argument can be any of the following:a string containing the filename to load host patterns from
a byte string containing host pattern data to load
an already loaded
SSHKnownHosts
object containing host patterns to match againstan alternate matching function which accepts a host, address, and port and returns lists of trusted host keys, trusted CA keys, and revoked keys to load
lists of trusted host keys, trusted CA keys, and revoked keys to load without doing any matching
If the port is not the default port and no match is found for it, the lookup is attempted again without a port number.
Logging¶
AsyncSSH supports logging through the standard Python logging
package.
Logging is done under the logger named 'asyncssh'
as well as a child
logger named 'asyncssh.sftp'
to allow different log levels to be set
for SFTP related log messages.
The base AsyncSSH log level can be set using the set_log_level()
function and the SFTP log level can be set using the set_sftp_log_level()
function. In addition, when either of these loggers is set to level DEBUG,
AsyncSSH provides fine-grained control over the level of debug logging
via the set_debug_level()
function.
AsyncSSH also provides logger objects as members of connection, channel, stream, and process objects that automatically log additional context about the connection or channel the logger is a member of. These objects can be used by application code to output custom log information associated with a particular connection or channel. Logger objects are also provided as members of SFTP client and server objects.
set_log_level¶
- asyncssh.set_log_level(level)[source]¶
Set the AsyncSSH log level
This function sets the log level of the AsyncSSH logger. It defaults to
'NOTSET
’, meaning that it will track the debug level set on the root Python logger.For additional control over the level of debug logging, see the function
set_debug_level()
for additional information.
set_sftp_log_level¶
- asyncssh.set_sftp_log_level(level)[source]¶
Set the AsyncSSH SFTP/SCP log level
This function sets the log level of the AsyncSSH SFTP/SCP logger. It defaults to
'NOTSET
’, meaning that it will track the debug level set on the main AsyncSSH logger.For additional control over the level of debug logging, see the function
set_debug_level()
for additional information.
set_debug_level¶
- asyncssh.set_debug_level(level)[source]¶
Set the AsyncSSH debug log level
This function sets the level of debugging logging done by the AsyncSSH logger, from the following options:
Level
Description
1
Minimal debug logging
2
Full debug logging
3
Full debug logging with packet dumps
The debug level defaults to level 1 (minimal debug logging).
Note
For this setting to have any effect, the effective log level of the AsyncSSH logger must be set to DEBUG.
Warning
Extreme caution should be used when setting debug level to 3, as this can expose user passwords in clear text. This level should generally only be needed when tracking down issues with malformed or incomplete packets.
- Parameters
level (
int
) – The debug level to set, as defined above.
Exceptions¶
PasswordChangeRequired¶
- exception asyncssh.PasswordChangeRequired(prompt, lang='en-US')[source]¶
SSH password change required
This exception is raised during password validation on the server to indicate that a password change is required. It should be raised when the password provided is valid but expired, to trigger the client to provide a new password.
BreakReceived¶
SignalReceived¶
TerminalSizeChanged¶
DisconnectError¶
- exception asyncssh.DisconnectError(code, reason, lang='en-US')[source]¶
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. See below for exception subclasses tied to specific disconnect reasons if you want to customize your handling by reason.
- Parameters
code (
int
) – Disconnect reason, taken from disconnect reason codesreason (
str
) – A human-readable reason for the disconnectlang (
str
) – (optional) The language the reason is in
- exception asyncssh.CompressionError(reason, lang='en-US')[source]¶
SSH compression error
This exception is raised when an error occurs while compressing or decompressing data sent on the SSH connection.
- exception asyncssh.ConnectionLost(reason, lang='en-US')[source]¶
SSH connection lost
This exception is raised when the SSH connection to the remote system is unexpectedly lost. It can also occur as a result of the remote system failing to respond to keepalive messages or as a result of a login timeout, when those features are enabled.
- exception asyncssh.HostKeyNotVerifiable(reason, lang='en-US')[source]¶
SSH host key not verifiable
This exception is raised when the SSH server’s host key or certificate is not verifiable.
- exception asyncssh.IllegalUserName(reason, lang='en-US')[source]¶
SSH illegal user name
This exception is raised when an error occurs while processing the username sent during the SSL handshake.
- exception asyncssh.KeyExchangeFailed(reason, lang='en-US')[source]¶
SSH key exchange failed
This exception is raised when the SSH key exchange fails.
- exception asyncssh.MACError(reason, lang='en-US')[source]¶
SSH MAC error
This exception is raised when an error occurs while processing the message authentication code (MAC) of a message on the SSH connection.
- exception asyncssh.PermissionDenied(reason, lang='en-US')[source]¶
SSH permission denied
This exception is raised when there are no authentication methods remaining to complete SSH client authentication.
- exception asyncssh.ProtocolError(reason, lang='en-US')[source]¶
SSH protocol error
This exception is raised when the SSH connection is disconnected due to an SSH protocol error being detected.
- exception asyncssh.ProtocolNotSupported(reason, lang='en-US')[source]¶
SSH protocol not supported
This exception is raised when the remote system sends an SSH protocol version which is not supported.
ChannelOpenError¶
- exception asyncssh.ChannelOpenError(code, reason, lang='en-US')[source]¶
SSH channel open error
This exception is raised by connection handlers to report channel open failures.
- Parameters
code (
int
) – Channel open failure reason, taken from channel open failure reason codesreason (
str
) – A human-readable reason for the channel open failurelang (
str
) – The language the reason is in
ChannelListenError¶
ProcessError¶
- exception asyncssh.ProcessError(env, command, subsystem, exit_status, exit_signal, returncode, stdout, stderr, reason='', lang='en-US')[source]¶
SSH Process error
This exception is raised when an
SSHClientProcess
exits with a non-zero exit status and error checking is enabled. In addition to the usual error code, reason, and language, it contains the following fields:Field
Description
Type
env
The environment the client requested to be set for the process
command
The command the client requested the process to execute (if any)
subsystem
The subsystem the client requested the process to open (if any)
exit_status
The exit status returned, or -1 if an exit signal is sent
exit_signal
The exit signal sent (if any) in the form of a tuple containing the signal name, a
bool
for whether a core dump occurred, a message associated with the signal, and the language the message was inreturncode
The exit status returned, or negative of the signal number when an exit signal is sent
stdout
The output sent by the process to stdout (if not redirected)
stderr
The output sent by the process to stderr (if not redirected)
TimeoutError¶
- exception asyncssh.TimeoutError(env, command, subsystem, exit_status, exit_signal, returncode, stdout, stderr, reason='', lang='en-US')[source]¶
SSH Process timeout error
This exception is raised when a timeout occurs when calling the
wait
method onSSHClientProcess
or therun
method onSSHClientConnection
. It is a subclass ofProcessError
and contains all of the fields documented there, including any output received on stdout and stderr prior to when the timeout occurred. It is also a subclass ofasyncio.TimeoutError
, for code that might be expecting that.
SFTPError¶
- exception asyncssh.SFTPError(code, reason, lang='en-US')[source]¶
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 (
int
) – Disconnect reason, taken from disconnect reason codesreason (
str
) – A human-readable reason for the disconnectlang (
str
) – (optional) The language the reason is in
- exception asyncssh.SFTPEOFError(reason='', lang='en-US')[source]¶
SFTP EOF error
This exception is raised when end of file is reached when reading a file or directory.
- exception asyncssh.SFTPNoSuchFile(reason, lang='en-US')[source]¶
SFTP no such file
This exception is raised when the requested file is not found.
- exception asyncssh.SFTPPermissionDenied(reason, lang='en-US')[source]¶
SFTP permission denied
This exception is raised when the permissions are not available to perform the requested operation.
- exception asyncssh.SFTPFailure(reason, lang='en-US')[source]¶
SFTP failure
This exception is raised when an unexpected SFTP failure occurs.
- exception asyncssh.SFTPBadMessage(reason, lang='en-US')[source]¶
SFTP bad message
This exception is raised when an invalid SFTP message is received.
- exception asyncssh.SFTPNoConnection(reason, lang='en-US')[source]¶
SFTP no connection
This exception is raised when an SFTP request is made on a closed SSH connection.
- exception asyncssh.SFTPConnectionLost(reason, lang='en-US')[source]¶
SFTP connection lost
This exception is raised when the SSH connection is lost or closed while making an SFTP request.
- exception asyncssh.SFTPOpUnsupported(reason, lang='en-US')[source]¶
SFTP operation unsupported
This exception is raised when the requested SFTP operation is not supported.
- exception asyncssh.SFTPInvalidHandle(reason, lang='en-US')[source]¶
SFTP invalid handle (SFTPv4+)
This exception is raised when the handle provided is invalid.
- exception asyncssh.SFTPNoSuchPath(reason, lang='en-US')[source]¶
SFTP no such path (SFTPv4+)
This exception is raised when the requested path is not found.
- exception asyncssh.SFTPFileAlreadyExists(reason, lang='en-US')[source]¶
SFTP file already exists (SFTPv4+)
This exception is raised when the requested file already exists.
- exception asyncssh.SFTPWriteProtect(reason, lang='en-US')[source]¶
SFTP write protect (SFTPv4+)
This exception is raised when a write is attempted to a file on read-only or write protected media.
- exception asyncssh.SFTPNoMedia(reason, lang='en-US')[source]¶
SFTP no media (SFTPv4+)
This exception is raised when there is no media in the requested drive.
- exception asyncssh.SFTPNoSpaceOnFilesystem(reason, lang='en-US')[source]¶
SFTP no space on filesystem (SFTPv5+)
This exception is raised when there is no space available on the filesystem a file is being written to.
- exception asyncssh.SFTPQuotaExceeded(reason, lang='en-US')[source]¶
SFTP quota exceeded (SFTPv5+)
This exception is raised when the user’s storage quota is exceeded.
- exception asyncssh.SFTPUnknownPrincipal(reason, lang='en-US', unknown_names=())[source]¶
SFTP unknown principal (SFTPv5+)
This exception is raised when a file owner or group is not reocgnized.
- exception asyncssh.SFTPLockConflict(reason, lang='en-US')[source]¶
SFTP lock conflict (SFTPv5+)
This exception is raised when a requested lock is held by another process.
- exception asyncssh.SFTPDirNotEmpty(reason, lang='en-US')[source]¶
SFTP directory not empty (SFTPv6+)
This exception is raised when a directory is not empty.
- exception asyncssh.SFTPNotADirectory(reason, lang='en-US')[source]¶
SFTP not a directory (SFTPv6+)
This exception is raised when a specified file is not a directory where one was expected.
- exception asyncssh.SFTPInvalidFilename(reason, lang='en-US')[source]¶
SFTP invalid filename (SFTPv6+)
This exception is raised when a filename is not valid.
- exception asyncssh.SFTPLinkLoop(reason, lang='en-US')[source]¶
SFTP link loop (SFTPv6+)
This exception is raised when a symbolic link loop is detected.
- exception asyncssh.SFTPCannotDelete(reason, lang='en-US')[source]¶
SFTP cannot delete (SFTPv6+)
This exception is raised when a file cannot be deleted.
- exception asyncssh.SFTPInvalidParameter(reason, lang='en-US')[source]¶
SFTP invalid parameter (SFTPv6+)
This exception is raised when parameters in a request are out of range or incompatible with one another.
- exception asyncssh.SFTPFileIsADirectory(reason, lang='en-US')[source]¶
SFTP file is a directory (SFTPv6+)
This exception is raised when a specified file is a directory where one isn’t allowed.
- exception asyncssh.SFTPByteRangeLockConflict(reason, lang='en-US')[source]¶
SFTP byte range lock conflict (SFTPv6+)
This exception is raised when a read or write request overlaps a byte range lock held by another process.
- exception asyncssh.SFTPByteRangeLockRefused(reason, lang='en-US')[source]¶
SFTP byte range lock refused (SFTPv6+)
This exception is raised when a request for a byte range lock was refused.
- exception asyncssh.SFTPDeletePending(reason, lang='en-US')[source]¶
SFTP delete pending (SFTPv6+)
This exception is raised when an operation was attempted on a file for which a delete operation is pending. another process.
- exception asyncssh.SFTPFileCorrupt(reason, lang='en-US')[source]¶
SFTP file corrupt (SFTPv6+)
This exception is raised when filesystem corruption is detected.
- exception asyncssh.SFTPOwnerInvalid(reason, lang='en-US')[source]¶
SFTP owner invalid (SFTPv6+)
This exception is raised when a principal cannot be assigned as the owner of a file.
- exception asyncssh.SFTPGroupInvalid(reason, lang='en-US')[source]¶
SFTP group invalid (SFTPv6+)
This exception is raised when a principal cannot be assigned as the primary group of a file.
KeyImportError¶
KeyExportError¶
KeyEncryptionError¶
KeyGenerationError¶
- exception asyncssh.KeyGenerationError[source]¶
Key generation error
This exception is raised by
generate_private_key()
,generate_user_certificate()
orgenerate_host_certificate()
when the requested parameters are unsupported.
ConfigParseError¶
Supported Algorithms¶
Algorithms can be specified as either a list of exact algorithm names or as a string of comma-separated algorithm names that may optionally include wildcards. An ‘*’ in a name matches zero or more characters and a ‘?’ matches exactly one character.
When specifying algorithms as a string, it can also be prefixed with ‘^’ to insert the matching algorithms in front of the default algorithms of that type, a ‘+’ to insert the matching algorithms after the default algorithms, or a ‘-’ to return the default algorithms with the matching algorithms removed.
Key exchange algorithms¶
The following are the default key exchange algorithms currently supported by AsyncSSH:
gss-curve25519-sha256gss-curve448-sha512gss-nistp521-sha512gss-nistp384-sha256gss-nistp256-sha256gss-1.3.132.0.10-sha256gss-gex-sha256gss-group14-sha256gss-group15-sha512gss-group16-sha512gss-group17-sha512gss-group18-sha512gss-group14-sha1sntrup761x25519-sha512@openssh.comcurve25519-sha256curve25519-sha256@libssh.orgcurve448-sha512ecdh-sha2-nistp521ecdh-sha2-nistp384ecdh-sha2-nistp256ecdh-sha2-1.3.132.0.10diffie-hellman-group-exchange-sha256diffie-hellman-group14-sha256diffie-hellman-group15-sha512diffie-hellman-group16-sha512diffie-hellman-group17-sha512diffie-hellman-group18-sha512diffie-hellman-group14-sha256@ssh.comdiffie-hellman-group14-sha1rsa2048-sha256
The following key exchange algorithms are supported by AsyncSSH, but disabled by default:
gss-gex-sha1gss-group1-sha1diffie-hellman-group-exchange-sha224@ssh.comdiffie-hellman-group-exchange-sha384@ssh.comdiffie-hellman-group-exchange-sha512@ssh.comdiffie-hellman-group-exchange-sha1diffie-hellman-group14-sha224@ssh.comdiffie-hellman-group15-sha256@ssh.comdiffie-hellman-group15-sha384@ssh.comdiffie-hellman-group16-sha384@ssh.comdiffie-hellman-group16-sha512@ssh.comdiffie-hellman-group18-sha512@ssh.comdiffie-hellman-group1-sha1rsa1024-sha1
GSS authentication support is only available when the gssapi package is installed on UNIX or the pywin32 package is installed on Windows.
Curve25519 and Curve448 support is available when OpenSSL 1.1.1 or later is installed. Alternately, Curve25519 is available when the libnacl package and libsodium library are installed.
SNTRUP support is available when the Open Quantum Safe (liboqs) dynamic library is installed.
Encryption algorithms¶
The following are the default encryption algorithms currently supported by AsyncSSH:
chacha20-poly1305@openssh.comaes256-gcm@openssh.comaes128-gcm@openssh.comaes256-ctraes192-ctraes128-ctr
The following encryption algorithms are supported by AsyncSSH, but disabled by default:
aes256-cbcaes192-cbcaes128-cbc3des-cbcblowfish-cbccast128-cbcseed-cbc@ssh.comarcfour256arcfour128arcfour
Chacha20-Poly1305 support is available when either OpenSSL 1.1.1b or later or the libnacl package and libsodium library are installed.
MAC algorithms¶
The following are the default MAC algorithms currently supported by AsyncSSH:
umac-64-etm@openssh.comumac-128-etm@openssh.comhmac-sha2-256-etm@openssh.comhmac-sha2-512-etm@openssh.comhmac-sha1-etm@openssh.comumac-64@openssh.comumac-128@openssh.comhmac-sha2-256hmac-sha2-512hmac-sha1hmac-sha256-2@ssh.comhmac-sha224@ssh.comhmac-sha256@ssh.comhmac-sha384@ssh.comhmac-sha512@ssh.com
The following MAC algorithms are supported by AsyncSSH, but disabled by default:
hmac-md5-etm@openssh.comhmac-sha2-256-96-etm@openssh.comhmac-sha2-512-96-etm@openssh.comhmac-sha1-96-etm@openssh.comhmac-md5-96-etm@openssh.comhmac-md5hmac-sha2-256-96hmac-sha2-512-96hmac-sha1-96hmac-md5-96
UMAC support is only available when the nettle library is installed.
Compression algorithms¶
The following are the default compression algorithms currently supported by AsyncSSH:
zlib@openssh.comnone
The following compression algorithms are supported by AsyncSSH, but disabled by default:
zlib
Signature algorithms¶
The following are the default public key signature algorithms currently supported by AsyncSSH:
x509v3-ssh-ed25519x509v3-ssh-ed448x509v3-ecdsa-sha2-nistp521x509v3-ecdsa-sha2-nistp384x509v3-ecdsa-sha2-nistp256x509v3-ecdsa-sha2-1.3.132.0.10x509v3-rsa2048-sha256x509v3-ssh-rsask-ssh-ed25519@openssh.comsk-ecdsa-sha2-nistp256@openssh.comssh-ed25519ssh-ed448ecdsa-sha2-nistp521ecdsa-sha2-nistp384ecdsa-sha2-nistp256ecdsa-sha2-1.3.132.0.10rsa-sha2-256rsa-sha2-512ssh-rsa-sha224@ssh.comssh-rsa-sha256@ssh.comssh-rsa-sha384@ssh.comssh-rsa-sha512@ssh.comssh-rsa
The following public key signature algorithms are supported by AsyncSSH, but disabled by default:
x509v3-ssh-dssssh-dss
Public key & certificate algorithms¶
The following are the default public key and certificate algorithms currently supported by AsyncSSH:
x509v3-ssh-ed25519x509v3-ssh-ed448x509v3-ecdsa-sha2-nistp521x509v3-ecdsa-sha2-nistp384x509v3-ecdsa-sha2-nistp256x509v3-ecdsa-sha2-1.3.132.0.10x509v3-rsa2048-sha256x509v3-ssh-rsask-ssh-ed25519-cert-v01@openssh.comsk-ecdsa-sha2-nistp256-cert-v01@openssh.comssh-ed25519-cert-v01@openssh.comssh-ed448-cert-v01@openssh.comecdsa-sha2-nistp521-cert-v01@openssh.comecdsa-sha2-nistp384-cert-v01@openssh.comecdsa-sha2-nistp256-cert-v01@openssh.comecdsa-sha2-1.3.132.0.10-cert-v01@openssh.comrsa-sha2-256-cert-v01@openssh.comrsa-sha2-512-cert-v01@openssh.comssh-rsa-cert-v01@openssh.comsk-ssh-ed25519@openssh.comsk-ecdsa-sha2-nistp256@openssh.comssh-ed25519ssh-ed448ecdsa-sha2-nistp521ecdsa-sha2-nistp384ecdsa-sha2-nistp256ecdsa-sha2-1.3.132.0.10rsa-sha2-256rsa-sha2-512ssh-rsa-sha224@ssh.comssh-rsa-sha256@ssh.comssh-rsa-sha384@ssh.comssh-rsa-sha512@ssh.comssh-rsa
The following public key and certificate algorithms are supported by AsyncSSH, but disabled by default:
x509v3-ssh-dssssh-dss-cert-v01@openssh.comssh-dss
Ed25519 and Ed448 support is available when OpenSSL 1.1.1b or later is installed. Alternately, Ed25519 is available when the libnacl package and libsodium library are installed.
Constants¶
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_CONNECTDISC_PROTOCOL_ERRORDISC_KEY_EXCHANGE_FAILEDDISC_RESERVEDDISC_MAC_ERRORDISC_COMPRESSION_ERRORDISC_SERVICE_NOT_AVAILABLEDISC_PROTOCOL_VERSION_NOT_SUPPORTEDDISC_HOST_KEY_NOT_VERIFIABLEDISC_CONNECTION_LOSTDISC_BY_APPLICATIONDISC_TOO_MANY_CONNECTIONSDISC_AUTH_CANCELLED_BY_USERDISC_NO_MORE_AUTH_METHODS_AVAILABLEDISC_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_PROHIBITEDOPEN_CONNECT_FAILEDOPEN_UNKNOWN_CHANNEL_TYPEOPEN_RESOURCE_SHORTAGE
In addition, AsyncSSH defines the following channel open failure reason codes:
OPEN_REQUEST_X11_FORWARDING_FAILEDOPEN_REQUEST_PTY_FAILEDOPEN_REQUEST_SESSION_FAILED
SFTP error codes¶
The following values defined in section 9.1 of the SSH File Transfer Protocol Internet Draft can be specified as SFTP error codes:
Error code |
Minimum SFTP version |
---|---|
FX_OK |
3 |
FX_EOF |
3 |
FX_NO_SUCH_FILE |
3 |
FX_PERMISSION_DENIED |
3 |
FX_FAILURE |
3 |
FX_BAD_MESSAGE |
3 |
FX_NO_CONNECTION |
3 |
FX_CONNECTION_LOST |
3 |
FX_OP_UNSUPPORTED |
3 |
FX_INVALID_HANDLE |
4 |
FX_NO_SUCH_PATH |
4 |
FX_FILE_ALREADY_EXISTS |
4 |
FX_WRITE_PROTECT |
4 |
FX_NO_MEDIA |
4 |
FX_NO_SPACE_ON_FILESYSTEM |
5 |
FX_QUOTA_EXCEEDED |
5 |
FX_UNKNOWN_PRINCIPAL |
5 |
FX_LOCK_CONFLICT |
5 |
FX_DIR_NOT_EMPTY |
6 |
FX_NOT_A_DIRECTORY |
6 |
FX_INVALID_FILENAME |
6 |
FX_LINK_LOOP |
6 |
FX_CANNOT_DELETE |
6 |
FX_INVALID_PARAMETER |
6 |
FX_FILE_IS_A_DIRECTORY |
6 |
FX_BYTE_RANGE_LOCK_CONFLICT |
6 |
FX_BYTE_RANGE_LOCK_REFUSED |
6 |
FX_DELETE_PENDING |
6 |
FX_FILE_CORRUPT |
6 |
FX_OWNER_INVALID |
6 |
FX_GROUP_INVALID |
6 |
FX_NO_MATCHING_BYTE_RANGE_LOCK |
6 |
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_ENDPTY_VINTRPTY_VQUITPTY_VERASEPTY_VKILLPTY_VEOFPTY_VEOLPTY_VEOL2PTY_VSTARTPTY_VSTOPPTY_VSUSPPTY_VDSUSPPTY_VREPRINTPTY_WERASEPTY_VLNEXTPTY_VFLUSHPTY_VSWTCHPTY_VSTATUSPTY_VDISCARDPTY_IGNPARPTY_PARMRKPTY_INPCKPTY_ISTRIPPTY_INLCRPTY_IGNCRPTY_ICRNLPTY_IUCLCPTY_IXONPTY_IXANYPTY_IXOFFPTY_IMAXBELPTY_ISIGPTY_ICANONPTY_XCASEPTY_ECHOPTY_ECHOEPTY_ECHOKPTY_ECHONLPTY_NOFLSHPTY_TOSTOPPTY_IEXTENPTY_ECHOCTLPTY_ECHOKEPTY_PENDINPTY_OPOSTPTY_OLCUCPTY_ONLCRPTY_OCRNLPTY_ONOCRPTY_ONLRETPTY_CS7PTY_CS8PTY_PARENBPTY_PARODDPTY_OP_ISPEEDPTY_OP_OSPEED