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
async def run_client():
async with asyncssh.connect('localhost') as conn:
result = await conn.run('echo "Hello!"', check=True)
print(result.stdout, end='')
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SSH connection failed: ' + str(exc))
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
- OpenSSH-compatible direct and forwarded UNIX domain socket channels
- Local and remote TCP/IP port forwarding
- Local and remote UNIX domain socket forwarding
- X11 forwarding support on both the client and the server
- 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
- Support for accessing keys managed by ssh-agent on UNIX systems
- Including agent forwarding support on both the client and the server
- Support for accessing keys managed by PuTTY’s Pageant agent on Windows
- 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-2016 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:
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.1 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://pypi.python.org/pypi/bcrypt if you want support for OpenSSH private key encryption.
- Install libsodium from https://github.com/jedisct1/libsodium and libnacl from https://pypi.python.org/pypi/libnacl if you want support for curve25519 Diffie Hellman key exchange, ed25519 keys, and the chacha20-poly1305 cipher.
- Install libnettle from http://www.lysator.liu.se/~nisse/nettle/ if you want support for UMAC cryptographic hashes.
- Install pypiwin32 from https://pypi.python.org/pypi/pypiwin32 if you want support for using the Pageant agent on Windows.
AsyncSSH defines the following optional PyPI extra packages to make it easy to install any or all of these dependencies:
bcryptlibnaclpypiwin32
For example, to install bcrypt and libnacl, you can run:
pip install 'asyncssh[bcrypt,libnacl]'
To install all three of these packages on a Windows system, you can run:
pip install 'asyncssh[bcrypt,libnacl,pypiwin32]'
Note that you will still need to manually install the libsodium library listed above for libnacl to work correctly and/or libnettle for UMAC support. Unfortunately, since libsodium and libnettle are not Python packages, they cannot be directly installed using pip.
Installing the development branch¶
If you would like to install the development branch of asyncssh directly from Github, you can use the following command to do this:
pip install git+https://github.com/ronf/asyncssh@develop
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 async def run_client(): async with asyncssh.connect('localhost') as conn: result = await conn.run('ls abc', check=True) print(result.stdout, end='') try: asyncio.get_event_loop().run_until_complete(run_client()) except (OSError, asyncssh.Error) as exc: sys.exit('SSH connection failed: ' + str(exc))
This example only uses the output on stdout, but output on stderr is also
collected as another attribute in the returned SSHCompletedProcess
object.
To check against a different set of server host keys, they can be provided in the known_hosts argument when the connection is opened:
async with asyncssh.connect('localhost', known_hosts='my_known_hosts') as conn:
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:
async with asyncssh.connect('localhost', username='user123') as conn:
To use a different set of client keys for authentication, they can be provided in the client_keys argument:
async with asyncssh.connect('localhost', client_keys=['my_ssh_key']) as conn:
Password authentication can be used by providing a password argument:
async with asyncssh.connect('localhost', password='secretpw') as conn:
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.
Callback example¶
AsyncSSH also provides APIs that use callbacks rather than “await” and “async
with”. Here’s the example above written using custom SSHClient
and
SSHClientSession
subclasses:
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.') async def run_client(): conn, client = await asyncssh.create_connection(MySSHClient, 'localhost') async with conn: chan, session = await conn.create_session(MySSHClientSession, 'ls abc') await 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))
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) async def run_client(): async with asyncssh.connect('localhost') as conn: chan, session = await conn.create_session(MySSHClientSession, 'ls abc') await 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))
If you need to distinguish output going to stdout vs. stderr, 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) async def run_client(): async with asyncssh.connect('localhost') as conn: chan, session = await conn.create_session(MySSHClientSession, 'ls abc') await 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))
Interactive input¶
The following example demonstrates sending interactive input to a remote
process. It executes the calculator program bc
and performs some basic
math calculations. Note that it uses the create_process
method rather than the run
method. This starts the process but doesn’t wait
for it to exit, allowing interaction with it.
import asyncio, asyncssh, sys async def run_client(): async with asyncssh.connect('localhost') as conn: async with conn.create_process('bc') as process: for op in ['2+2', '1*2*3*4', '2^32']: process.stdin.write(op + '\n') result = await process.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
I/O redirection¶
The following example shows how to pass a fixed input string to a remote process and redirect the resulting output to the local file ‘/tmp/stdout’. Input lines containing 1, 2, and 3 are passed into the ‘tail -r’ command and the output written to ‘/tmp/stdout’ should contain the reversed lines 3, 2, and 1:
import asyncio, asyncssh, sys async def run_client(): async with asyncssh.connect('localhost') as conn: await conn.run('tail -r', input='1\n2\n3\n', stdout='/tmp/stdout') try: asyncio.get_event_loop().run_until_complete(run_client()) except (OSError, asyncssh.Error) as exc: sys.exit('SSH connection failed: ' + str(exc))
The stdin
, stdout
, and stderr
arguments support redirecting
to a variety of locations include local files, pipes, and sockets as
well as SSHReader
or SSHWriter
objects associated with
other remote SSH processes. Here’s an example of piping stdout from a
local process to a remote process:
import asyncio, asyncssh, subprocess, sys async def run_client(): async with asyncssh.connect('localhost') as conn: local_proc = subprocess.Popen(r'echo "1\n2\n3"', shell=True, stdout=subprocess.PIPE) remote_result = await conn.run('tail -r', stdin=local_proc.stdout) print(remote_result.stdout, end='') try: asyncio.get_event_loop().run_until_complete(run_client()) except (OSError, asyncssh.Error) as exc: sys.exit('SSH connection failed: ' + str(exc))
Here’s an example of piping one remote process to another:
import asyncio, asyncssh, sys async def run_client(): async with asyncssh.connect('localhost') as conn: proc1 = await conn.create_process(r'echo "1\n2\n3"') proc2_result = await conn.run('tail -r', stdin=proc1.stdout) print(proc2_result.stdout, end='') try: asyncio.get_event_loop().run_until_complete(run_client()) except (OSError, asyncssh.Error) as exc: sys.exit('SSH connection failed: ' + str(exc))
In this example both remote processes are running on the same SSH connection, but this redirection can just as easily be used between SSH sessions associated with connections going to different servers.
Checking exit status¶
The following example shows how to test the exit status of a remote process:
import asyncio, asyncssh, sys async def run_client(): async with asyncssh.connect('localhost') as conn: result = await conn.run('ls abc') if result.exit_status == 0: print(result.stdout, end='') else: print(result.stderr, end='', file=sys.stderr) print('Program exited with status %d' % result.exit_status, 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))
If an exit signal is received, the exit status will be set to -1 and exit
signal information is provided in the exit_signal
attribute of the
returned SSHCompletedProcess
.
If the check
argument in run
is set
to True
, any abnormal exit will raise a ProcessError
exception
instead of returning an SSHCompletedProcess
.
Running multiple clients¶
The following example shows how to run multiple clients in parallel and process the results when all of them have completed:
import asyncio, asyncssh async def run_client(host, command): async with asyncssh.connect(host) as conn: return await conn.run(command) async def run_multiple_clients(): # Put your lists of hosts here hosts = 5 * ['localhost'] tasks = (run_client(host, 'ls abc') for host in hosts) results = await asyncio.gather(*tasks, return_exceptions=True) for i, result in enumerate(results, 1): if isinstance(result, Exception): print('Task %d failed: %s' % (i, str(result))) elif result.exit_status != 0: print('Task %d exited with status %s:' % (i, result.exit_status)) print(result.stderr, end='') else: print('Task %d succeeded:' % i) print(result.stdout, end='') print(75*'-') asyncio.get_event_loop().run_until_complete(run_multiple_clients())
Results could be processed as they became available by setting up a
loop which repeatedly called asyncio.wait()
instead of calling
asyncio.gather()
.
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 async def run_client(): async with asyncssh.connect('localhost') as conn: result = await conn.run('env', env={'LANG': 'en_GB', 'LC_COLLATE': 'C'}) print(result.stdout, end='') 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 async def run_client(): async with asyncssh.connect('localhost') as conn: result = await conn.run('echo $TERM; stty size', term_type='xterm-color', term_size=(80, 24)) print(result.stdout, end='') 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 async def run_client(): async with asyncssh.connect('localhost') as conn: listener = await conn.forward_local_port('', 8080, 'www.google.com', 80) await 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 async def run_client(): async with asyncssh.connect('localhost') as conn: listener = await conn.forward_local_port('', 0, 'www.google.com', 80) print('Listening on port %s...' % listener.get_port()) await 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 async def run_client(): async with asyncssh.connect('localhost') as conn: listener = await conn.forward_remote_port('', 8080, 'localhost', 80) await 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') async def run_client(): global conn async with asyncssh.connect('localhost') as conn: listener = await conn.create_server(connection_requested, '', 8080) await 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) async def run_client(): async with asyncssh.connect('localhost') as conn: chan, session = await 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() await 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 async def run_client(): async with asyncssh.connect('localhost') as conn: reader, writer = await 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 = await 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() async def run_client(): async with asyncssh.connect('localhost') as conn: server = await conn.create_server(connection_requested, '', 8888, encoding='utf-8') if server: await 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 async def handle_connection(reader, writer): while not reader.at_eof(): data = await 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 async def run_client(): async with asyncssh.connect('localhost') as conn: server = await conn.start_server(connection_requested, '', 8888, encoding='utf-8') await 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 requesting the download of a file:
import asyncio, asyncssh, sys async def run_client(): async with asyncssh.connect('localhost') as conn: async with conn.start_sftp_client() as sftp: await 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:
await 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”:
await 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' } def handle_session(stdin, stdout, stderr): stdout.write('Welcome to my SSH server, %s!\n' % stdout.channel.get_extra_info('username')) stdout.channel.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 async def start_server(): await asyncssh.create_server(MySSHServer, '', 8022, server_host_keys=['ssh_host_key'], session_factory=handle_session) 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 matching the username in
a directory called authorized_keys
.
import asyncio, asyncssh, sys def handle_session(stdin, stdout, stderr): stdout.write('Welcome to my SSH server, %s!\n' % stdout.channel.get_extra_info('username')) stdout.channel.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 async def start_server(): await asyncssh.create_server(MySSHServer, '', 8022, server_host_keys=['ssh_host_key'], session_factory=handle_session) 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. In this case, a custom SSHServer
subclass
is no longer required, and so the listen()
function can be used in
place of create_server()
.
import asyncio, asyncssh, sys def handle_session(stdin, stdout, stderr): stdout.write('Welcome to my SSH server, %s!\n' % stdout.channel.get_extra_info('username')) stdout.channel.exit(0) async def start_server(): await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], authorized_client_keys='ssh_user_ca', session_factory=handle_session) 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 adds a column of numbers, displaying the total when it receives EOF.
import asyncio, asyncssh, sys async def handle_session(stdin, stdout, stderr): stdout.write('Enter numbers one per line, or EOF when done:\n') total = 0 try: async for line in stdin: line = line.rstrip('\n') if line: try: total += int(line) except ValueError: stderr.write('Invalid number: %s\n' % line) except asyncssh.BreakReceived: pass stdout.write('Total = %s\n' % total) stdout.channel.exit(0) async def start_server(): await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], authorized_client_keys='ssh_user_ca', session_factory=handle_session) 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()
Callback example¶
Here’s an example of the server above written using callbacks in
custom SSHServer
and SSHServerSession
subclasses.
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 session_started(self): self._chan.write('Enter numbers one per line, or EOF when done:\n') 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\n' % line) self._input = lines[-1] def eof_received(self): self._chan.write('Total = %s\n' % self._total) self._chan.exit(0) def break_received(self, msec): self.eof_received() class MySSHServer(asyncssh.SSHServer): def session_requested(self): return MySSHServerSession() async def start_server(): await 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()
Serving multiple clients¶
The following is a slightly more complicated example showing how a server can manage multiple simultaneous clients. It implements a basic chat service, where clients can send messages to one other.
import asyncio, asyncssh, sys class ChatClient: _clients = [] def __init__(self, stdin, stdout): self._stdin = stdin self._stdout = stdout @classmethod async def handle_session(cls, stdin, stdout, stderr): await cls(stdin, stdout).run() def write(self, msg): self._stdout.write(msg) def broadcast(self, msg): for client in self._clients: if client != self: client.write(msg) async def run(self): self.write('Welcome to chat!\n\n') self.write('Enter your name: ') name = (await self._stdin.readline()).rstrip('\n') self.write('\n%d other users are connected.\n\n' % len(self._clients)) self._clients.append(self) self.broadcast('*** %s has entered chat ***\n' % name) try: async for line in self._stdin: self.broadcast('%s: %s' % (name, line)) except asyncssh.BreakReceived: pass self.broadcast('*** %s has left chat ***\n' % name) self._clients.remove(self) async def start_server(): await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], authorized_client_keys='ssh_user_ca', session_factory=ChatClient.handle_session) 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()
Line editing¶
When SSH clients request a pseudo-terminal, they generally default to sending input a character at a time and expect the remote system to provide character echo and line editing. To better support interactive applications like the one above, AsyncSSH defaults to providing basic line editing for server sessions which request a pseudo-terminal.
When thise line editor is enabled, it defaults to delivering input to
the application a line at a time. Applications can switch between line
and character at a time input using the set_line_mode()
method. Also, when in line
mode, applications can enable or disable echoing of input using the
set_echo()
method. The
following code provides an example of this.
import asyncio, asyncssh, sys async def handle_session(stdin, stdout, stderr): stdout.write('Welcome to my SSH server, %s!\n\n' % stdout.channel.get_extra_info('username')) stdin.channel.set_echo(False) stdout.write('Tell me a secret: ') secret = await stdin.readline() stdin.channel.set_line_mode(False) stdout.write('\nYour secret is safe with me! Press any key to exit...') await stdin.read(1) stdout.write('\n') stdout.channel.exit(0) async def start_server(): await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], authorized_client_keys='ssh_user_ca', session_factory=handle_session) 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 async def handle_session(stdin, stdout, stderr): env = stdout.channel.get_environment() if env: keywidth = max(map(len, env.keys()))+1 stdout.write('Environment:\n') for key, value in env.items(): stdout.write(' %-*s %s\n' % (keywidth, key+':', value)) stdout.channel.exit(0) else: stderr.write('No environment sent.\n') stdout.channel.exit(1) async def start_server(): await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], authorized_client_keys='ssh_user_ca', session_factory=handle_session) 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 async def handle_session(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('\nTry resizing your window!\n') while not stdin.at_eof(): try: await 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('\n') async def start_server(): await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], authorized_client_keys='ssh_user_ca', session_factory=handle_session) 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') async def start_server(): await 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 async def start_server(): await 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') async def start_server(): await 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 async def handle_connection(reader, writer): while not reader.at_eof(): data = await 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') async def start_server(): await 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 async def start_server(): await 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) async def start_server(): await 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.