Establishing an SSH client and server with the asyncSSH and asyncio modules

Establishing an SSH client and server with the asyncSSH and asyncio modules

AsyncSSH and asyncio are Python modules that provide tools for asynchronous communication with SSH servers. They enable you to handle multiple SSH connections concurrently, improving performance and responsiveness in applications that require frequent communication with remote servers.

AsyncSSH:

AsyncSSH is an asynchronous SSH client library that provides a high-level interface for interacting with SSH servers using asynchronous programming techniques. It allows you to establish asynchronous connections, execute commands, transfer files, and manage SFTP sessions without blocking the main thread of execution.

Key Features of AsyncSSH:

asyncio:

asyncio is a standard library in Python that provides a framework for asynchronous programming. It allows you to write concurrent code that utilizes event loops and callbacks to manage multiple tasks without blocking the main thread.

Benefits of Using AsyncSSH and asyncio:

Application Scenarios:

Integration with AsyncSSH and asyncio:

AsyncSSH integrates seamlessly with the asyncio framework, enabling you to leverage its asynchronous features and event loops for efficient SSH operations. You can define coroutines for SSH tasks, utilize asynchronous callbacks, and manage concurrent SSH connections within the asyncio event loop.

In summary, AsyncSSH and asyncio provide powerful tools for asynchronous SSH communication in Python. Their combination enables developers to build responsive and scalable applications that handle multiple SSH connections efficiently, improving performance and resource utilization.

Overview SSH client

This Python script utilizes the asyncssh library to establish an SSH (Secure Shell) connection to a remote server asynchronously. It then executes a specified command on the remote server and prints the output.

Importing Libraries

Python
import asyncssh
import asyncio
import getpass

Async Function: execute_command

Python
async def execute_command(host, command, username, password):
    async with asyncssh.connect(host, username=username, password=password) as connection:
        result = await connection.run(command)
        return result.stdout

  • Parameters:

    • host: Target SSH server hostname.
    • command: Command to be executed on the remote server.
    • username: SSH username.
    • password: SSH password.
  • Functionality:

    • Establishes an asynchronous SSH connection to the specified host using the provided credentials.
    • Executes the specified command on the remote server.
    • Returns the standard output (stdout) of the command.

Main Block

Python
if __name__ == '__main__':
    hostname = input("Enter the target hostname: ")
    command = input("Enter command: ")
    username = input("Enter username: ")
    password = getpass.getpass(prompt="Enter password: ")
    loop = asyncio.get_event_loop()
    output_command = loop.run_until_complete(execute_command(hostname, command, username, password))
    print(output_command)

Input Gathering

Python
import asyncssh
import asyncio
import getpass

async def execute_command(host, command, username, password):
    async with asyncssh.connect(host, username = username, password= password) as connection:
        result = await connection.run(command)
        return result.stdout

if __name__ == '__main__':
    hostname = input("Enter the target hostname: ")
    command = input("Enter command: ")
    username = input("Enter username: ")
    password = getpass.getpass(prompt="Enter password: ")
    loop = asyncio.get_event_loop()
    output_command = loop.run_until_complete(execute_command(hostname, command, username, password))
    print(output_command)

Note

Overview SSH server

This Python script uses the asyncssh library to create a simple asynchronous SSH server. The server listens for incoming SSH connections on localhost at port 22 and prints a message when a connection is established.

Importing Libraries

Python
import asyncio
import asyncssh
import sys

MySSHServer Class

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

Async Function: start_server

Python
async def start_server():
    await asyncssh.create_server(MySSHServer, 'localhost', 22,
                                 server_host_keys=['/etc/ssh/ssh_host_ecdsa_key'])

Main Block

Python
loop = asyncio.get_event_loop()

try:
    print("Starting SSH server on localhost:22")
    loop.run_until_complete(start_server())
except (OSError, asyncssh.Error) as exc:
    sys.exit('Error starting server: ' + str(exc))

loop.run_forever()
Python
import asyncio, asyncssh, sys

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

async def start_server():
    await asyncssh.create_server(MySSHServer, 'localhost', 22,
                                 server_host_keys=['/etc/ssh/ssh_host_ecdsa_key'])

loop = asyncio.get_event_loop()

try:
    print("Starting SSH server on localhost:22")
    loop.run_until_complete(start_server())
except (OSError, asyncssh.Error) as exc:
    sys.exit('Error starting server: ' + str(exc))

loop.run_forever()

Note

Exit mobile version