Paramiko
lastmod 2025-04-23created 2015-11-296 edits
Paramiko is a pure-Python 1 (3.6+) implementation of the SSHv2 protocol 2, providing both client and server functionality. It provides the foundation for the high-level SSH library Fabric, which is what we recommend you use for common client use-cases such as running remote shell commands or transferring files.
Checking whether the SSH Agent is running
If you cannot check with an environment variable such as SSH_AGENT_PID, check with this, since it uses paramiko internally.
SSH Tunneling Forward Example
You can also use sshtunnel.
import paramiko
import socket
import select
def handler(chan, host, port):
sock = socket.socket()
try:
sock.connect((host, port))
except Exception as e:
print(f"Forwarding request to {host}:{port} failed: {e}")
return
while True:
r, _, _ = select.select([sock, chan], [], [])
if sock in r:
data = sock.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
sock.send(data)
def forward_tunnel(local_port, remote_host, remote_port, transport):
transport.request_port_forward('localhost', local_port)
while True:
chan = transport.accept(1000)
if chan is None:
continue
handler(chan, remote_host, remote_port)
# Setup connection
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('ssh.example.com', username='your_username', password='your_password')
transport = client.get_transport()
forward_tunnel(10022, '127.0.0.1', 3306, transport)
Troubleshooting
SSH agent is not running or no keys are available
Occurs when the SSH Agent is not running.
def prompt_for_key():
keys = paramiko.Agent().get_keys()
if not keys:
> raise SshAgentKeyError(SshAgentKeyError.E_NO_KEYS)
E sagecipher.cipher.SshAgentKeyError: SSH agent is not running or no keys are available
See also
- Sagecipher (used to check the SSH Agent)
Favorite site
- Paramiko web site
- paramiko/paramiko: The leading native Python SSHv2 protocol library.
- The ultimate simple SSH module for Python
Pages that link here