# AsyncSSH: Asynchronous SSH for Python

AsyncSSH is a Python package which provides an asynchronous client and server implementation of the SSHv2 protocol on top of the Python 3.4+ asyncio framework.

    import asyncio, asyncssh, sys

    @asyncio.coroutine
    def run_client():
        with (yield from asyncssh.connect('localhost')) as conn:
            stdin, stdout, stderr = yield from conn.open_session('echo "Hello!"')
            output = yield from stdout.read()
            print(output, end='')

            status = stdout.channel.get_exit_status()
            if status:
                print('Program exited with status %d' % status, file=sys.stderr)
            else:
                print('Program exited successfully')

    asyncio.get_event_loop().run_until_complete(run_client())

Check out the examples to get started!

## Features

- Full support for SSHv2 and SFTP client and server functions
  - Shell, command, and subsystem channels
  - Environment variables, terminal type, and window size
  - Direct and forwarded TCP/IP channels
  - Local and remote TCP/IP port forwarding
  - SFTP protocol version 3 with OpenSSH extensions
- Multiple simultaneous sessions on a single SSH connection
- Multiple SSH connections in a single event loop
- Byte and string based I/O with settable encoding
- A variety of key exchange, encryption, and MAC algorithms
- Support for gzip compression
  - Including OpenSSH variant to delay compression until after auth
- Password, public key, and keyboard-interactive user authentication methods
- Many types and formats of public keys and certificates
- OpenSSH-style known_hosts file support
- OpenSSH-style authorized_keys file support
- Compatibility with OpenSSH “Encrypt then MAC” option for better security
- Time and byte-count based session key renegotiation
- Designed to be easy to extend to support new forms of key exchange, authentication, encryption, and compression algorithms

## License

This package is released under the following terms:

> Copyright (c) 2013-2015 by Ron Frederick <ronf@timeheart.net>. All rights reserved.

> This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution and is available at:

> > http://www.eclipse.org/legal/epl-v10.html

For more information about this license, please see the Eclipse Public License FAQ.

## Prerequisites

To use `asyncssh`, you need the following:

- Python 3.4 or later
- cryptography (PyCA) 1.0.0 or later

## Installation

Install AsyncSSH by running:

>     pip install asyncssh

### Optional Extras

There are some optional modules you can install to enable additional functionality:

- Install bcrypt from https://code.google.com/p/py-bcrypt if you want support for OpenSSH private key encryption.
- Install libsodium from https://github.com/jedisct1/libsodium and libnacl from https://github.com/saltstack/libnacl if you want support for curve25519 Diffie Hellman key exchange, ed25519 keys, and the chacha20-poly1305 cipher.

AsyncSSH defines the following optional PyPI extra packages to make it easy to install any or all of these dependencies:

> bcrypt
> libnacl

For example, to install all of these, you can run:

>     pip install 'asyncssh[bcrypt,libnacl]'

Note that you will still need to manually install the libsodium library listed above for libnacl to work correctly. Unfortunately, since libsodium is not a Python package, it cannot be directly installed using pip.

## Mailing Lists

Three mailing lists are available for AsyncSSH:

- asyncssh-announce@googlegroups.com: Project announcements
- asyncssh-dev@googlegroups.com: Development discussions
- asyncssh-users@googlegroups.com: End-user discussions

# Client Examples

## Simple client

The following code shows an example of a simple SSH client which logs into localhost and lists files in a directory named ‘abc’ under the user’s home directory. The username provided is the logged in user, and the user’s default SSH client keys or certificates are presented during authentication. The server’s host key is checked against the user’s SSH known_hosts file and the connection will fail if there’s no entry for localhost there or if the key doesn’t match.

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def data_received(self, data, datatype):
>             print(data, end='')

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     class MySSHClient(asyncssh.SSHClient):
>         def connection_made(self, conn):
>             print('Connection made to %s.' % conn.get_extra_info('peername')[0])

>         def auth_completed(self):
>             print('Authentication successful.')

>     @asyncio.coroutine
>     def run_client():
>         conn, client = yield from asyncssh.create_connection(MySSHClient, 'localhost')

>         with conn:
>             chan, session = yield from conn.create_session(MySSHClientSession, 'ls abc')
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

To check against a different set of server host keys, they can be read and provided in the known_hosts argument when the `SSHClient` instance is created:

>     conn, client = yield from asyncssh.create_connection(MySSHClient, 'localhost',
>                                                          known_hosts='my_known_hosts')

Server host key checking can be disabled by setting the known_hosts argument to `None`, but that’s not recommended as it makes the connection vulnerable to a man-in-the-middle attack.

To log in as a different remote user, the username argument can be provided:

>     conn, client = yield from asyncssh.create_connection(MySSHClient, 'localhost',
>                                                          username='user123')

To use a different set of client keys for authentication, they can be read and provided in the client_keys argument:

>     conn, client = yield from asyncssh.create_connection(MySSHClient, 'localhost',
>                                                          client_keys=['my_ssh_key'])

Password authentication can be used by providing a password argument:

>     conn, client = yield from asyncssh.create_connection(MySSHClient, 'localhost',
>                                                          password='secretpw')

Any of the arguments above can be combined together as needed. If client keys and a password are both provided, either may be used depending on what forms of authentication the server supports and whether the authentication with them is successful.

In cases where you don’t need to customize callbacks on the SSHClient class, this code can be simplified somewhat to:

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def data_received(self, data, datatype):
>             print(data, end='')

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_session(MySSHClientSession, 'ls abc')
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

## Handling of stderr

The above code doesn’t distinguish output going to stdout vs. stderr, but that’s easy to do with the following change:

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def data_received(self, data, datatype):
>             if datatype == asyncssh.EXTENDED_DATA_STDERR:
>                 print(data, end='', file=sys.stderr)
>             else:
>                 print(data, end='')

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_session(MySSHClientSession, 'ls abc')
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

## Simple client with input

The following example demonstrates sending input to a remote program. It executes the calculator program `bc` and performs some basic math calculations.

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def next_operation(self):
>             if self._operations:
>                 operation = self._operations.pop(0)
>                 print(operation, '= ', end='')
>                 self._chan.write(operation + '\n')
>             else:
>                 self._chan.write_eof()

>         def connection_made(self, chan):
>             self._chan = chan

>         def session_started(self):
>             self._operations = ['2+2', '1*2*3*4', '2^32']
>             self.next_operation()

>         def data_received(self, data, datatype):
>             print(data, end='')

>             if '\n' in data:
>                 self.next_operation()

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_session(MySSHClientSession, 'bc')
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

Note that input is not sent on the channel until the `session_started()` method is called, and `write_eof()` is used to signal the end of input, causing the ‘bc’ program to exit.

This example can be simplified by using the higher-level “streams” API. With that, callbacks aren’t needed. Here’s the streams version of the above example, using `open_session` instead of `create_session`:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             stdin, stdout, stderr = yield from conn.open_session('bc')

>             for op in ['2+2', '1*2*3*4', '2^32']:
>                 stdin.write(op + '\n')
>                 result = yield from stdout.readline()
>                 print(op, '=', result, end='')

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

When run, this program should produce the following output:

>     2+2 = 4
>     1*2*3*4 = 24
>     2^32 = 4294967296

## Checking exit status

The following example is a variation of the simple client which shows how to receive the remote program’s exit status using the `exit_status_received` callback.

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def data_received(self, data, datatype):
>             if datatype == asyncssh.EXTENDED_DATA_STDERR:
>                 print(data, end='', file=sys.stderr)
>             else:
>                 print(data, end='')

>         def exit_status_received(self, status):
>             if status:
>                 print('Program exited with status %d' % status, file=sys.stderr)
>             else:
>                 print('Program exited successfully')

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_session(MySSHClientSession, 'ls abc')
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

From servers that support it, exit signals can also be received using `exit_signal_received`.

Exit status can be also queried after the channel has closed by using the methods `get_exit_status` and `get_exit_signal`. This is how it is done when using the streams API, since callbacks aren’t available there.

## Setting environment variables

The following example demonstrates setting environment variables for the remote session and displaying them by executing the ‘env’ command.

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def data_received(self, data, datatype):
>             print(data, end='')

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_session(MySSHClientSession, 'env',
>                                                            env={ 'LANG': 'en_GB',
>                                                                  'LC_COLLATE': 'C'})
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

Any number of environment variables can be passed in the dictionary given to `create_session()`. Note that SSH servers may restrict which environment variables (if any) are accepted, so this feature may require setting options on the SSH server before it will work.

## Setting terminal information

The following example demonstrates setting the terminal type and size passed to the remote session.

>     import asyncio, asyncssh, sys

>     class MySSHClientSession(asyncssh.SSHClientSession):
>         def data_received(self, data, datatype):
>             print(data, end='')

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH session error: ' + str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_session(MySSHClientSession,
>                                                            'echo $TERM; stty size',
>                                                            term_type='xterm-color',
>                                                            term_size=(80, 24))
>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

Note that this will cause AsyncSSH to request a pseudo-tty from the server. When a pseudo-tty is used, the server will no longer send output going to stderr with a different data type. Instead, it will be mixed with output going to stdout (unless it is redirected elsewhere by the remote command).

## Port forwarding

The following example demonstrates the client setting up a local TCP listener on port 8080 and requesting that connections which arrive on that port be forwarded across SSH to the server and on to port 80 on `www.google.com`:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             listener = yield from conn.forward_local_port('', 8080, 'www.google.com', 80)
>             yield from listener.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

To listen on a dynamically assigned port, the client can pass in `0` as the listening port. If the listener is successfully opened, the selected port will be available via the `get_port()` method on the returned listener object:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             listener = yield from conn.forward_local_port('', 0, 'www.google.com', 80)
>             print('Listening on port %s...' % listener.get_port())
>             yield from listener.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

The client can also request remote port forwarding from the server. The following example shows the client requesting that the server listen on port 8080 and that connections arriving there be forwarded across SSH and on to port 80 on `localhost`:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             listener = yield from conn.forward_remote_port('', 8080, 'localhost', 80)
>             yield from listener.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

To limit which connections are accepted or dynamically select where to forward traffic to, the client can implement their own session factory and call `forward_connection()` on the connections they wish to forward and raise an error on those they wish to reject:

>     import asyncio, asyncssh, sys

>     def connection_requested(orig_host, orig_port):
>         global conn

>         if orig_host in ('127.0.0.1', '::1'):
>             return conn.forward_connection('localhost', 80)
>         else:
>             raise asyncssh.ChannelOpenError(
>                 asyncssh.OPEN_ADMINISTRATIVELY_PROHIBITED,
>                 'Connections only allowed from localhost')

>     @asyncio.coroutine
>     def run_client():
>         global conn

>         with (yield from asyncssh.connect('localhost')) as conn:
>             listener = yield from conn.create_server(connection_requested, '', 8080)
>             yield from listener.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

Just as with local listeners, the client can request remote port forwarding from a dynamic port by passing in `0` as the listening port and then call `get_port()` on the returned listener to determine which port was selected.

## Direct TCP connections

The client can also ask the server to open a TCP connection and directly send and receive data on it by using the `create_connection()` method on the `SSHClientConnection` object. In this example, a connection is attempted to port 80 on `www.google.com` and an HTTP HEAD request is sent for the document root.

Note that unlike sessions created with `create_session()`, the I/O on these connections defaults to sending and receiving bytes rather than strings, allowing arbitrary binary data to be exchanged. However, this can be changed by setting the encoding to use when the connection is created.

>     import asyncio, asyncssh, sys

>     class MySSHTCPSession(asyncssh.SSHTCPSession):
>         def data_received(self, data, datatype):
>             # We use sys.stdout.buffer here because we're writing bytes
>             sys.stdout.buffer.write(data)

>         def connection_lost(self, exc):
>             if exc:
>                 print('Direct connection error:', str(exc), file=sys.stderr)

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             chan, session = yield from conn.create_connection(MySSHTCPSession,
>                                                               'www.google.com', 80)

>             # By default, TCP connections send and receive bytes
>             chan.write(b'HEAD / HTTP/1.0\r\n\r\n')
>             chan.write_eof()

>             yield from chan.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

To use the streams API to open a direct connection, you can use `open_connection` instead of `create_connection`:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             reader, writer = yield from conn.open_connection('www.google.com', 80)

>             # By default, TCP connections send and receive bytes
>             writer.write(b'HEAD / HTTP/1.0\r\n\r\n')
>             writer.write_eof()

>             # We use sys.stdout.buffer here because we're writing bytes
>             response = yield from reader.read()
>             sys.stdout.buffer.write(response)

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

## Forwarded TCP connections

The client can also directly process data from incoming TCP connections received on the server. The following example demonstrates the client requesting that the server listen on port 8888 and forward any received connections back to it over SSH. It then has a simple handler which echoes any data it receives back to the sender.

As in the direct TCP connection example above, the default would be to send and receive bytes on this connection rather than strings, but here we set the encoding explicitly so all data is sent and received as strings:

>     import asyncio, asyncssh, sys

>     class MySSHTCPSession(asyncssh.SSHTCPSession):
>         def connection_made(self, chan):
>             self._chan = chan

>         def data_received(self, data, datatype):
>             self._chan.write(data)

>     def connection_requested(orig_host, orig_port):
>         print('Connection received from %s, port %s' % (orig_host, orig_port))
>         return MySSHTCPSession()

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             server = yield from conn.create_server(connection_requested, '', 8888,
>                                                    encoding='utf-8')

>             if server:
>                 yield from server.wait_closed()
>             else:
>                 print('Listener couldn''t be opened.', file=sys.stderr)

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

To use the streams API to open a listening connection, you can use `start_server` instead of `create_server`:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def handle_connection(reader, writer):
>         while not reader.at_eof():
>             data = yield from reader.read(8192)
>             writer.write(data)

>         writer.close()

>     def connection_requested(orig_host, orig_port):
>         print('Connection received from %s, port %s' % (orig_host, orig_port))
>         return handle_connection

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             server = yield from conn.start_server(connection_requested, '', 8888,
>                                                   encoding='utf-8')
>             yield from server.wait_closed()

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH connection failed: ' + str(exc))

## SFTP client

AsyncSSH also provides SFTP support. The following code shows an example of starting an SFTP client and requestng the download of a file:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def run_client():
>         with (yield from asyncssh.connect('localhost')) as conn:
>             with (yield from conn.start_sftp_client()) as sftp:
>                 yield from sftp.get('example.txt')

>     try:
>         asyncio.get_event_loop().run_until_complete(run_client())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SFTP operation failed: ' + str(exc))

To recursively download a directory, preserving access and modification times and permissions on the files, the preserve and recurse arguments can be included:

>     yield from sftp.get('example_dir', preserve=True, recurse=True)

Wild card pattern matching is supported by the `mget`, `mput`, and `mcopy` methods. The following downloads all files with extension “txt”:

>     yield from sftp.mget('*.txt')

See the `SFTPClient` documentation for the full list of available actions.

# Server Examples

## Simple server

The following code shows an example of a simple SSH server which listens for connections on port 8022, does password authentication, and prints a message when users authenticate successfully and start a shell.

>     # To run this program, the file ``ssh_host_key`` must exist with an SSH
>     # private key in it to use as a server host key. An SSH host certificate
>     # can optionally be provided in the file ``ssh_host_key-cert.pub``.

>     import asyncio, asyncssh, crypt, sys

>     passwords = {'guest': '',                 # guest account with no password
>                  'user123': 'qV2iEadIGV2rw'   # password of 'secretpw'
>                 }

>     class MySSHServerSession(asyncssh.SSHServerSession):
>         def shell_requested(self):
>             return True

>         def connection_made(self, chan):
>             self._chan = chan

>         def session_started(self):
>             self._chan.write('Welcome to my SSH server, %s!\r\n' %
>                                  self._chan.get_extra_info('username'))
>             self._chan.exit(0)

>     class MySSHServer(asyncssh.SSHServer):
>         def connection_made(self, conn):
>             print('SSH connection received from %s.' %
>                       conn.get_extra_info('peername')[0])

>         def connection_lost(self, exc):
>             if exc:
>                 print('SSH connection error: ' + str(exc), file=sys.stderr)
>             else:
>                 print('SSH connection closed.')

>         def begin_auth(self, username):
>             # If the user's password is the empty string, no auth is required
>             return passwords.get(username) != ''

>         def password_auth_supported(self):
>             return True

>         def validate_password(self, username, password):
>             pw = passwords.get(username, '*')
>             return crypt.crypt(password, pw) == pw

>         def session_requested(self):
>             return MySSHServerSession()

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'])

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

To authenticate with SSH client keys or certificates, the server would look something like the following. Client and certificate authority keys for each user need to be placed in a file in authorized_keys format named based on the username in a directory called `authorized_keys`.

>     import asyncio, asyncssh, sys

>     class MySSHServerSession(asyncssh.SSHServerSession):
>         def connection_made(self, chan):
>             self._chan = chan

>         def shell_requested(self):
>             return True

>         def session_started(self):
>             self._chan.write('Welcome to my SSH server, %s!\r\n' %
>                                  self._chan.get_extra_info('username'))
>             self._chan.exit(0)

>     class MySSHServer(asyncssh.SSHServer):
>         def connection_made(self, conn):
>             self._conn = conn

>         def begin_auth(self, username):
>             try:
>                 self._conn.set_authorized_keys('authorized_keys/%s' % username)
>             except IOError:
>                 pass

>             return True

>         def session_requested(self):
>             return MySSHServerSession()

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'])

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

It is also possible to use a single authorized_keys file for all users. This is common when using certificates, as AsyncSSH can automatically enforce that the certificates presented have a principal in them which matches the username. This would look something like the following.

>     import asyncio, asyncssh, sys

>     class MySSHServerSession(asyncssh.SSHServerSession):
>         def connection_made(self, chan):
>             self._chan = chan

>         def shell_requested(self):
>             return True

>         def session_started(self):
>             self._chan.write('Welcome to my SSH server, %s!\r\n' %
>                                  self._chan.get_extra_info('username'))
>             self._chan.exit(0)

>     class MySSHServer(asyncssh.SSHServer):
>         def session_requested(self):
>             return MySSHServerSession()

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'],
>                                           authorized_client_keys='ssh_user_ca')

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

## Simple server with input

The following example demonstrates reading input in a server session. It will sum a column of numbers, displaying the total and closing the connection when it receives EOF. Note that this is not an interactive application, so no echoing of user input is provided. You’ll need to have the SSH client read from a file or pipe rather than the terminal or tell it not to allocate a pty for this to work right.

>     import asyncio, asyncssh, sys

>     class MySSHServerSession(asyncssh.SSHServerSession):
>         def __init__(self):
>             self._input = ''
>             self._total = 0

>         def connection_made(self, chan):
>             self._chan = chan

>         def shell_requested(self):
>             return True

>         def data_received(self, data, datatype):
>             self._input += data

>             lines = self._input.split('\n')
>             for line in lines[:-1]:
>                 try:
>                     if line:
>                         self._total += int(line)
>                 except ValueError:
>                     self._chan.write_stderr('Invalid number: %s\r\n' % line)

>             self._input = lines[-1]

>         def eof_received(self):
>             self._chan.write('Total = %s\r\n' % self._total)
>             self._chan.exit(0)

>     class MySSHServer(asyncssh.SSHServer):
>         def session_requested(self):
>             return MySSHServerSession()

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'],
>                                           authorized_client_keys='ssh_user_ca')

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

Here’s an example of this server written using the streams API. In this case, `listen()` is used in place of `create_server()` since a custom subclass of `SSHServer` is not required. The handler coroutine to call to handle new sessions is specified using the `session_factory` argument. When a new session is requested, the handler coroutine is called with AsyncSSH stream objects representing stdin, stdout, and stderr that it can use to perform I/O.

This example also shows how to catch exceptions thrown when break messages, signals, or terminal size changes are received.

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def handle_connection(stdin, stdout, stderr):
>         total = 0

>         try:
>             while not stdin.at_eof():
>                 try:
>                     line = yield from stdin.readline()
>                 except (asyncssh.BreakReceived, asyncssh.SignalReceived):
>                     # Exit if the client sends a break or signal
>                     break
>                 except asyncssh.TerminalSizeChanged:
>                     # Ignore terminal size changes
>                     continue

>                 line = line.rstrip('\n')
>                 if line:
>                     try:
>                         total += int(line)
>                     except ValueError:
>                         stderr.write('Invalid number: %s\r\n' % line)

>             stdout.write('Total = %s\r\n' % total)
>             stdout.channel.exit(0)
>         except BrokenPipeError:
>             # The channel is already closed here, so we can't send an exit status
>             stdout.close()

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'],
>                                    authorized_client_keys='ssh_user_ca',
>                                    session_factory=handle_connection)

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

## Getting environment variables

The following example demonstrates reading environment variables set by the client. It will show all of the variables set by the client, or return an error if none are set. Note that SSH clients may restrict which environment variables (if any) are sent by default, so you may need to set options in the client to get it to do so.

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def handle_connection(stdin, stdout, stderr):
>         env = stdout.channel.get_environment()
>         if env:
>             keywidth = max(map(len, env.keys()))+1
>             stdout.write('Environment:\r\n')
>             for key, value in env.items():
>                 stdout.write('  %-*s %s\r\n' % (keywidth, key+':', value))
>             stdout.channel.exit(0)
>         else:
>             stderr.write('No environment sent.\r\n')
>             stdout.channel.exit(1)

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'],
>                                    authorized_client_keys='ssh_user_ca',
>                                    session_factory=handle_connection)

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

## Getting terminal information

The following example demonstrates reading the client’s terminal type and window size, and handling window size changes during a session.

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def handle_connection(stdin, stdout, stderr):
>         term_type = stdout.channel.get_terminal_type()
>         width, height, pixwidth, pixheight = stdout.channel.get_terminal_size()

>         stdout.write('Terminal type: %s, size: %sx%s' % (term_type, width, height))
>         if pixwidth and pixheight:
>             stdout.write(' (%sx%s pixels)' % (pixwidth, pixheight))
>         stdout.write('\r\nTry resizing your window!\r\n')

>         while not stdin.at_eof():
>             try:
>                 line = yield from stdin.read()
>             except asyncssh.TerminalSizeChanged as exc:
>                 stdout.write('New window size: %sx%s' % (exc.width, exc.height))
>                 if exc.pixwidth and exc.pixheight:
>                     stdout.write(' (%sx%s pixels)' % (exc.pixwidth, exc.pixheight))
>                 stdout.write('\r\n')

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'],
>                                    authorized_client_keys='ssh_user_ca',
>                                    session_factory=handle_connection)

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

## Port forwarding

The following example demonstrates a server accepting port forwarding requests from clients, but only when they are destined to port 80. When such a connection is received, a connection is attempted to the requested host and port and data is bidirectionally forwarded over SSH from the client to this destination. Requests by the client to connect to any other port are rejected.

>     import asyncio, asyncssh, sys

>     class MySSHServer(asyncssh.SSHServer):
>         def connection_requested(self, dest_host, dest_port, orig_host, orig_port):
>             if dest_port == 80:
>                 return True
>             else:
>                 raise asyncssh.ChannelOpenError(
>                           asyncssh.OPEN_ADMINISTRATIVELY_PROHIBITED,
>                           'Only connections to port 80 are allowed')

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'],
>                                           authorized_client_keys='ssh_user_ca')

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH server failed: ' + str(exc))

>     loop.run_forever()

The server can also support forwarding inbound TCP connections back to the client. The following example demonstrates a server which will accept requests like this from clients, but only to listen on port 8080. When such a connection is received, the client is notified and data is bidirectionally forwarded from the incoming connection over SSH to the client.

>     import asyncio, asyncssh, sys

>     class MySSHServer(asyncssh.SSHServer):
>         def server_requested(self, listen_host, listen_port):
>             return listen_port == 8080

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'],
>                                           authorized_client_keys='ssh_user_ca')

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH server failed: ' + str(exc))

>     loop.run_forever()

## Direct TCP connections

The server can also accept direct TCP connection requests from the client and process the data on them itself. The following example demonstrates a server which accepts requests to port 7 (the “echo” port) for any host and echoes the data itself rather than forwarding the connection:

>     import asyncio, asyncssh, sys

>     class MySSHTCPSession(asyncssh.SSHTCPSession):
>         def connection_made(self, chan):
>             self._chan = chan

>         def data_received(self, data, datatype):
>             self._chan.write(data)

>     class MySSHServer(asyncssh.SSHServer):
>         def connection_requested(self, dest_host, dest_port, orig_host, orig_port):
>             if dest_port == 7:
>                 return MySSHTCPSession()
>             else:
>                 raise asyncssh.ChannelOpenError(
>                           asyncssh.OPEN_ADMINISTRATIVELY_PROHIBITED,
>                           'Only echo connections allowed')

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'],
>                                           authorized_client_keys='ssh_user_ca')

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH server failed: ' + str(exc))

>     loop.run_forever()

Here’s an example of this server written using the streams API. In this case, `connection_requested()` returns a handler coroutine instead of a session object. When a new direct TCP connection is opened, the handler coroutine is called with AsyncSSH stream objects which can be used to perform I/O on the tunneled connection.

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def handle_connection(reader, writer):
>         while not reader.at_eof():
>             data = yield from reader.read(8192)

>             try:
>                 writer.write(data)
>             except BrokenPipeError:
>                 break

>         writer.close()

>     class MySSHServer(asyncssh.SSHServer):
>         def connection_requested(self, dest_host, dest_port, orig_host, orig_port):
>             if dest_port == 7:
>                 return handle_connection
>             else:
>                 raise asyncssh.ChannelOpenError(
>                           asyncssh.OPEN_ADMINISTRATIVELY_PROHIBITED,
>                           'Only echo connections allowed')

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.create_server(MySSHServer, '', 8022,
>                                           server_host_keys=['ssh_host_key'],
>                                           authorized_client_keys='ssh_user_ca')

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('SSH server failed: ' + str(exc))

>     loop.run_forever()

## SFTP server

The following example shows how to start an SFTP server with default behavior:

>     import asyncio, asyncssh, sys

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'],
>                                    authorized_client_keys='ssh_user_ca',
>                                    sftp_factory=True)

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

A subclass of `SFTPServer` can be provided as the value of the SFTP factory to override specific behavior. For example, the following code remaps path names so that each user gets access to only their own individual directory under `/tmp/sftp`:

>     import asyncio, asyncssh, os, sys

>     class MySFTPServer(asyncssh.SFTPServer):
>         def __init__(self, conn):
>             root = '/tmp/sftp/' + conn.get_extra_info('username')
>             os.makedirs(root, exist_ok=True)
>             super().__init__(conn, chroot=root)

>     @asyncio.coroutine
>     def start_server():
>         yield from asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'],
>                                    authorized_client_keys='ssh_user_ca',
>                                    sftp_factory=MySFTPServer)

>     loop = asyncio.get_event_loop()

>     try:
>         loop.run_until_complete(start_server())
>     except (OSError, asyncssh.Error) as exc:
>         sys.exit('Error starting server: ' + str(exc))

>     loop.run_forever()

More complex path remapping can be performed by implementing the `map_path` and `reverse_map_path` methods. Individual SFTP actions can also be overridden as needed. See the `SFTPServer` documentation for the full list of methods to override.