Mock SSH Server
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
-
ImportError: No module named 'mockssh'
cause The `mock-ssh-server` package is not installed or the import path is incorrect.fixEnsure the package is installed: `pip install mock-ssh-server`. The correct import is `from mockssh import MockSSH`. -
paramiko.ssh_exception.AuthenticationException: Authentication failed.
cause The username or password provided by the client does not match any user configured in the `MockSSH` server instance.fixVerify that the `users` dictionary passed to `MockSSH` contains the correct `username: password` pair that your client is attempting to use. -
socket.error: [Errno 111] Connection refused
cause The mock SSH server is either not running, or the client is attempting to connect to the wrong host or port.fixCheck that the `MockSSH` server is started and running within its context manager. Verify that the client's `hostname` and `port` parameters exactly match those provided by the `MockSSH` instance (e.g., `s.port`).
Warnings
- gotcha Versions prior to 0.3.0 were known to experience occasional deadlocks, particularly when interacting with real OpenSSH clients. This could lead to testing hangs or instability.
- gotcha Before version 0.9.0, customizing the authentication class was not directly supported via the API. Users might have resorted to workarounds or found their customization options limited.
- gotcha When generating host keys (e.g., `paramiko.RSAKey.generate()`), `mock-ssh-server` implicitly relies on `paramiko`'s underlying dependencies like `cryptography`. Missing or misconfigured `cryptography` installations can lead to errors during key generation.
Install
-
pip install mock-ssh-server
Imports
- MockSSH
from mockssh import MockSSH
Quickstart
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.")