Mock SSH Server

0.9.1 · active · verified Fri Apr 17

mock-ssh-server is a Python library providing a mock SSH server for testing purposes. It allows developers to create controlled SSH environments to test clients without needing a real SSH server. The current version is 0.9.1, and it generally follows an infrequent release cadence, driven by feature additions and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a mock SSH server with defined users and then connects to it using a Paramiko SSH client to execute a simple command. This confirms the server is operational and authentication works.

import paramiko
from mockssh import MockSSH
import socket # For example error handling

# 1. Define users for the mock SSH server
users = {
    "testuser": "testpassword",
    "admin": "securepass"
}

# 2. Generate a host key for the server (essential for real SSH clients)
# In a real application, you might load a persistent key.
server_host_key = paramiko.RSAKey.generate(2048)

print("Starting Mock SSH server...")
# 3. Start the mock SSH server in a context manager
with MockSSH(users, host='127.0.0.1', rsa_key=server_host_key) as s:
    server_port = s.port
    print(f"Mock SSH server running on 127.0.0.1:{server_port}")

    # 4. Demonstrate a client connection using paramiko
    print("\nAttempting to connect with Paramiko client...")
    client = paramiko.SSHClient()
    # Automatically add new host keys (for testing, not recommended for production)
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(
            hostname='127.0.0.1',
            port=server_port,
            username='testuser',
            password='testpassword'
        )
        print("Client connected successfully to mock SSH server.")

        # Execute a simple command
        stdin, stdout, stderr = client.exec_command('echo "Hello from mock SSH client!"')
        output = stdout.read().decode().strip()
        error = stderr.read().decode().strip()

        print(f"Command output: '{output}'")
        if error:
            print(f"Command error: '{error}'")

    except paramiko.AuthenticationException:
        print("Authentication failed for 'testuser'! Check username/password.")
    except paramiko.SSHException as e:
        print(f"SSH connection failed: {e}")
    except socket.error as e:
        print(f"Socket error: {e}. Is the server running and accessible?")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        if client.get_transport() and client.get_transport().is_active():
            client.close()
            print("Client connection closed.")

print("Mock SSH server context manager exited. Server is stopped.")

view raw JSON →