ZetCode

Python paramiko

last modified November 17, 2026 Python 3.15

In this article we show how to work with the SSH protocol in Python using the paramiko library.

SSH (Secure Shell) is a network protocol for secure remote login, command execution, and file transfer over an untrusted network. An SSH server listens on TCP port 22 by default. The server proves its identity with a host key, and the client authenticates with a password or a key pair. SFTP is a file transfer protocol that runs over an SSH connection.

Paramiko is a pure-Python implementation of the SSHv2 protocol, with cryptography provided by the cryptography package. It provides both client and server functionality, and it is the base of tools such as Fabric. The examples use paramiko 5.1.

$ pip install paramiko

A test SSH server

To run the examples, we need an SSH server. We run OpenSSH in a Docker container, so the examples do not touch a real machine. The image is based on Debian; it has a user user7 with the s3cret password. BusyBox provides a small web server for the port forwarding example.

Dockerfile
FROM debian:trixie-slim

RUN apt-get update \
    && apt-get install -y --no-install-recommends openssh-server busybox \
    && rm -rf /var/lib/apt/lists/* \
    && mkdir -p /run/sshd \
    && useradd --create-home --shell /bin/bash user7 \
    && echo 'user7:s3cret' | chpasswd

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D", "-e"]

The openssh-server package generates the server's host keys during installation. The sshd daemon runs in the foreground with -D and logs to standard error with -e.

We build the image and start a container with port 22 published on port 2222 of the local machine. The 127.0.0.1 prefix makes the port reachable only from this computer. The home directory of user7 contains a few sample files: data.txt and the docs and logs directories.

$ docker build -q -t ssh-test .
sha256:ee417998b09dd550834be53bbe8e9a49cabdd941e2777661daa03a26fa8d29b2
$ docker run -d --name ssh-test -p 127.0.0.1:2222:22 ssh-test
cf10a4b58d67809e3b247b3e6de08697b7f0a9d2ff75b46bdef35cd8371752a5
$ docker ps --format '{{.Names}} {{.Status}} {{.Ports}}'
ssh-test Up 1 second 127.0.0.1:2222->22/tcp

Host keys

On the first connection to a server, the client must verify the server's host key; otherwise an attacker could impersonate the server. OpenSSH stores the trusted keys in the ~/.ssh/known_hosts file.

The ssh-keyscan tool fetches the host key; we save it to a local known_hosts file used by the examples. Before trusting a scanned key on a real network, compare its fingerprint, printed by ssh-keygen -l, with the one shown by the server's administrator. A host on a non-standard port is stored as [host]:port.

$ ssh-keyscan -p 2222 -t ed25519 localhost > known_hosts
$ cat known_hosts
[localhost]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEBbrAKDwFT3TvVZthH0I5xFUktcf/yKxqhLs46Rl92g
$ ssh-keygen -l -f known_hosts
256 SHA256:2iHTDpMd4NPJZukxKjXTesLDuwe+dTASQWS0re4fz6U [localhost]:2222 (ED25519)

Executing a command

In the first example, we connect to the server with a password and execute a command.

exec_cmd.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    stdin, stdout, stderr = client.exec_command('uname -sr; whoami; pwd')
    print(stdout.read().decode(), end='')

We create an SSHClient and use it as a context manager, which closes the connection at the end. The load_host_keys method loads the trusted host keys from our known_hosts file; for the user's standard file, call load_system_host_keys.

client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

The connect method opens the connection, checks the host key, and authenticates the user.

stdin, stdout, stderr = client.exec_command('uname -sr; whoami; pwd')
print(stdout.read().decode(), end='')

The exec_command method runs the command on the server through the user's shell, so we can join several commands with semicolons. It returns file-like objects for the command's standard input, output, and error streams. The read method returns bytes, which we decode to a string. The uname command reports the host's kernel, because containers share the kernel with the host.

$ python exec_cmd.py
Linux 6.8.0-149-generic
user7
/home/user7

Unknown host keys

If the host key is not known, SSHClient refuses the connection. The default RejectPolicy raises an SSHException.

unknown_host.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

with paramiko.SSHClient() as client:
    try:
        client.connect(HOST, port=PORT, username=USER, password=PASSWORD)
    except paramiko.SSHException as e:
        print(f'{type(e).__name__}: {e}')

with paramiko.Transport((HOST, PORT)) as transport:
    transport.start_client()
    key = transport.get_remote_server_key()
    print(key.get_name(), key.fingerprint)

The first connection fails, because we did not load any host keys. The second part uses the lower-level Transport class to start the SSH handshake and fetch the server's key without authenticating. The fingerprint property gives the key's SHA256 fingerprint in the same format as ssh-keygen -l, so we can compare the two.

$ python unknown_host.py
SSHException: Server '[localhost]:2222' not found in known_hosts
ssh-ed25519 SHA256:2iHTDpMd4NPJZukxKjXTesLDuwe+dTASQWS0re4fz6U

AutoAddPolicy

The AutoAddPolicy accepts and stores unknown host keys automatically. Many tutorials use it, but it disables protection against man-in-the-middle attacks on the first connection, and it hides changed keys when the known hosts are not saved and reloaded.

auto_add.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

with paramiko.SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    client.save_host_keys('new_known_hosts')

with open('new_known_hosts') as f:
    print(f.read(), end='')

The key accepted by the policy is added to the client's host keys, and save_host_keys writes them to a file in the known_hosts format. Use this policy only for throwaway test servers; for real hosts, distribute the known host keys ahead of time.

$ python auto_add.py
[localhost]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEBbrAKDwFT3TvVZthH0I5xFUktcf/yKxqhLs46Rl92g

Exit status and standard error

A remote command reports success or failure with its exit status and writes error messages to standard error. Both must be checked; reading only stdout hides failures.

exit_status.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

commands = ['ls docs', 'ls /nonexistent', 'grep -c i data.txt', 'exit 3']

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    for cmd in commands:
        stdin, stdout, stderr = client.exec_command(cmd)

        out = stdout.read().decode().strip()
        err = stderr.read().decode().strip()
        status = stdout.channel.recv_exit_status()

        print(f'$ {cmd}  (exit status {status})')
        if out:
            print(f'  stdout: {out!r}')
        if err:
            print(f'  stderr: {err!r}')

We run four commands. The recv_exit_status method of the channel waits for the command to finish and returns its exit status. We read both streams before waiting for the status: a command with a lot of output would otherwise block when the channel's window fills up.

$ python exit_status.py
$ ls docs  (exit status 0)
  stdout: 'notes\nreadme.txt'
$ ls /nonexistent  (exit status 2)
  stderr: "ls: cannot access '/nonexistent': No such file or directory"
$ grep -c i data.txt  (exit status 0)
  stdout: '2'
$ exit 3  (exit status 3)

Streaming output

The stdout object can be iterated line by line while the command is still running. This is useful for long-running commands, such as builds or log monitoring.

streaming.py
import time

import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

cmd = 'for i in 1 2 3; do echo "step $i"; sleep 1; done; echo done'

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    start = time.monotonic()
    stdin, stdout, stderr = client.exec_command(cmd)

    for line in stdout:
        print(f'{time.monotonic() - start:3.0f}s {line.rstrip()}')

The remote loop prints a line every second. The program prints each line as soon as it arrives, prefixed with the time elapsed since the command was started.

$ python streaming.py
  0s step 1
  1s step 2
  2s step 3
  3s done

Sending input to a command

The stdin object sends data to the command's standard input.

stdin_input.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

fruits = ['apple', 'plum', 'apple', 'pear', 'plum', 'apple']

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    stdin, stdout, stderr = client.exec_command('sort | uniq -c | sort -rn')

    stdin.write('\n'.join(fruits) + '\n')
    stdin.channel.shutdown_write()

    print(stdout.read().decode(), end='')

We send a list of fruits to a pipeline that counts the occurrences of each line. The shutdown_write method of the channel closes the input stream; without it, sort would wait for more data forever.

$ python stdin_input.py
      3 apple
      2 plum
      1 pear

Public key authentication

Passwords in source code are a security risk. Public key authentication is the preferred method: the server stores the user's public key in ~/.ssh/authorized_keys, and the client proves that it has the matching private key.

install_key.py
import stat
from pathlib import Path

import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

public_key = Path('id_ed25519.pub').read_text()

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    with client.open_sftp() as sftp:
        try:
            sftp.mkdir('.ssh', mode=0o700)
        except OSError:
            pass

        with sftp.open('.ssh/authorized_keys', 'a') as f:
            f.write(public_key)

        sftp.chmod('.ssh/authorized_keys', 0o600)
        attrs = sftp.stat('.ssh/authorized_keys')
        print(stat.filemode(attrs.st_mode), attrs.st_size)

The program logs in with the password and installs our public key with SFTP. The .ssh directory must not be accessible by other users, and the authorized_keys file must be writable only by its owner, or the server ignores it. The stat method returns the remote file's attributes; we print its permissions and size.

key_auth.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'

key = paramiko.PKey.from_path('id_ed25519')
print(type(key).__name__, key.fingerprint)

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, pkey=key,
                   allow_agent=False, look_for_keys=False)

    transport = client.get_transport()
    print(transport.is_authenticated(), transport.get_username())
    print(transport.remote_version)

    stdin, stdout, stderr = client.exec_command('whoami')
    print(stdout.read().decode(), end='')

The PKey.from_path method loads a private key and detects its type; here it is an Ed25519 key. We pass the key to connect with the pkey parameter. The allow_agent=False and look_for_keys=False options make paramiko use only the given key, not keys from an SSH agent or the ~/.ssh directory. The remote_version attribute holds the server's identification string.

We generate a new Ed25519 key pair with ssh-keygen, without a passphrase for the demo, install the public key, and log in with the private key. An encrypted private key is loaded with PKey.from_path(path, passphrase=...).

$ ssh-keygen -q -t ed25519 -N '' -C 'paramiko demo' -f id_ed25519
$ python install_key.py
-rw------- 95
$ python key_auth.py
Ed25519Key SHA256:ueSTseG5pIFHuRYEb41XjsJGbJd7PlWhXnWnSQDNqck
True user7
SSH-2.0-OpenSSH_10.0p2 Debian-7+deb13u4
user7

Handling connection errors

Paramiko signals authentication failures and protocol errors with its own exceptions; network problems raise standard OSError subclasses.

errors.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

attempts = [
    ('wrong password', dict(hostname=HOST, port=PORT, password='wrong')),
    ('closed port', dict(hostname=HOST, port=2223, password=PASSWORD)),
    ('unreachable host', dict(hostname='10.255.255.1', port=22,
                              password=PASSWORD, timeout=2)),
]

for label, params in attempts:
    with paramiko.SSHClient() as client:
        client.load_host_keys('known_hosts')
        try:
            client.connect(username=USER, allow_agent=False,
                           look_for_keys=False, **params)
        except paramiko.AuthenticationException as e:
            print(f'{label}: authentication failed: {e}')
        except paramiko.SSHException as e:
            print(f'{label}: SSH error: {e}')
        except OSError as e:
            print(f'{label}: {type(e).__name__}: {e}')

We try three failing connections. A wrong password raises AuthenticationException, a subclass of SSHException, so it must be caught first. A closed port raises NoValidConnectionsError after paramiko tries all addresses of the host. An unreachable host raises TimeoutError after the number of seconds given in the timeout parameter; without it, the connection attempt can block for minutes.

$ python errors.py
wrong password: authentication failed: Authentication failed.
closed port: NoValidConnectionsError: [Errno None] Unable to connect to port 2223 on 127.0.0.1
unreachable host: TimeoutError: timed out

SFTP upload and download

The open_sftp method opens an SFTP session over the existing SSH connection. The put method uploads a local file and get downloads a remote file.

report.csv
id,product,amount
1,keyboard,2
2,mouse,5
3,monitor,1

We upload this local CSV file.

sftp_transfer.py
from pathlib import Path

import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

def progress(sent, total):
    print(f'  {sent}/{total} bytes')


with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    with client.open_sftp() as sftp:
        sftp.mkdir('uploads')
        attrs = sftp.put('report.csv', 'uploads/report.csv', callback=progress)
        print(f'uploaded {attrs.st_size} bytes')

        sftp.get('data.txt', 'data.txt')

print(Path('data.txt').read_text().split())

We create the remote uploads directory and upload the file to it. The callback function is called with the number of bytes transferred so far and the total size; for small files it is called once. The put method returns the attributes of the remote file. We then download the remote data.txt file and read it locally. Relative remote paths are resolved against the user's home directory.

$ python sftp_transfer.py
  53/53 bytes
uploaded 53 bytes
['sky', 'cloud', 'rain', 'snow', 'wind']

SFTP directory listing

The listdir method returns the names in a remote directory, and listdir_attr returns SFTPAttributes objects with the size, permissions, and modification time of each entry.

sftp_list.py
import stat
from datetime import datetime

import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    with client.open_sftp() as sftp:
        print(sftp.normalize('.'))
        print(sorted(sftp.listdir()))

        for attr in sorted(sftp.listdir_attr('docs'), key=lambda a: a.filename):
            mode = stat.filemode(attr.st_mode)
            modified = datetime.fromtimestamp(attr.st_mtime)
            print(f'{mode} {attr.st_size:5} {modified:%Y-%m-%d %H:%M} {attr.filename}')

The normalize method converts a remote path to an absolute one; for ., it returns the home directory. The names come in arbitrary order, so we sort them. The stat.filemode function formats the permission bits like ls -l. The modification times are shown in the local time zone of the client.

$ python sftp_list.py
/home/user7
['.bash_logout', '.bashrc', '.profile', '.ssh', 'data.txt', 'docs', 'logs', 'uploads']
drwxr-xr-x  4096 2026-11-02 11:15 notes
-rw-r--r--    14 2026-11-02 11:15 readme.txt

Remote files

The open method of the SFTP client returns a file-like object for a remote file. The client also has methods to rename, remove, and stat remote files.

sftp_files.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    with client.open_sftp() as sftp:
        sftp.chdir('docs')
        print(sftp.getcwd())

        with sftp.open('words.txt', 'w') as f:
            f.write('falcon\nowl\nhawk\n')

        with sftp.open('words.txt') as f:
            for line in f:
                print(line.rstrip())

        sftp.rename('words.txt', 'birds.txt')
        print(sftp.stat('birds.txt').st_size)

        sftp.remove('birds.txt')

        try:
            sftp.stat('birds.txt')
        except FileNotFoundError as e:
            print(f'FileNotFoundError: {e}')

The chdir method sets the current directory of the SFTP session; getcwd returns it. We write a remote file, read it back line by line, rename it, print its size, and remove it. Paramiko maps the SFTP no such file status to the built-in FileNotFoundError.

$ python sftp_files.py
/home/user7/docs
falcon
owl
hawk
16
FileNotFoundError: [Errno 2] No such file

Walking a remote directory tree

The SFTP client has no recursive listing method. We write one with listdir_attr and the stat.S_ISDIR function.

sftp_tree.py
import stat

import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

def walk(sftp, path, depth=0):
    for attr in sorted(sftp.listdir_attr(path), key=lambda a: a.filename):
        if attr.filename.startswith('.'):
            continue
        if stat.S_ISDIR(attr.st_mode):
            print(f'{"    " * depth}{attr.filename}/')
            walk(sftp, f'{path}/{attr.filename}', depth + 1)
        else:
            print(f'{"    " * depth}{attr.filename} ({attr.st_size} B)')


with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    with client.open_sftp() as sftp:
        walk(sftp, '.')

The walk function prints the entries of a directory and calls itself for subdirectories. Hidden files, such as the .ssh directory and the shell's dot files, are skipped. The tree includes the uploads directory created earlier.

$ python sftp_tree.py
data.txt (25 B)
docs/
    notes/
        todo.txt (21 B)
    readme.txt (14 B)
logs/
    app.log (16 B)
uploads/
    report.csv (53 B)

Port forwarding

SSH can tunnel TCP connections. A direct-tcpip channel asks the server to open a connection to a host and port as seen from the server. This is how we reach a database or a web service that listens only on the server's loopback interface.

tunnel.py
import paramiko

HOST = 'localhost'
PORT = 2222
USER = 'user7'
PASSWORD = 's3cret'

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(HOST, port=PORT, username=USER, password=PASSWORD)

    transport = client.get_transport()
    channel = transport.open_channel('direct-tcpip', ('127.0.0.1', 8080),
                                     ('127.0.0.1', 0))

    channel.sendall(b'GET / HTTP/1.0\r\nHost: localhost\r\n\r\n')

    response = b''
    while data := channel.recv(4096):
        response += data

    channel.close()

headers, _, body = response.decode().partition('\r\n\r\n')
print(headers.splitlines()[0])
print(body, end='')

The open_channel method of the transport opens a channel to port 8080 on the server's 127.0.0.1; the last argument is the originating address reported to the server. The channel behaves like a socket: we send an HTTP request with sendall and read the response with recv until the server closes the connection.

We create a page and start the BusyBox web server inside the container on 127.0.0.1:8080. The port is not published, so the program can reach it only through the SSH tunnel.

$ docker exec ssh-test sh -c 'mkdir -p /srv/www && echo "internal status: OK" > /srv/www/index.html'
$ docker exec ssh-test busybox httpd -p 127.0.0.1:8080 -h /srv/www
$ python tunnel.py
HTTP/1.1 200 OK
internal status: OK

SSH config files

OpenSSH reads host aliases and connection options from ~/.ssh/config. Paramiko's SSHConfig class parses this format, but SSHClient does not apply it on its own; we pass the looked-up values to connect.

ssh_config
Host testbox
    HostName localhost
    Port 2222
    User user7
    IdentityFile id_ed25519
    IdentitiesOnly yes

The configuration defines the testbox alias for our test server.

ssh_config.py
import paramiko

config = paramiko.SSHConfig.from_path('ssh_config')
host = config.lookup('testbox')

print(host)

with paramiko.SSHClient() as client:
    client.load_host_keys('known_hosts')
    client.connect(host['hostname'], port=int(host['port']),
                   username=host['user'], key_filename=host['identityfile'],
                   allow_agent=False, look_for_keys=False)

    stdin, stdout, stderr = client.exec_command('hostname; id')
    print(stdout.read().decode(), end='')

The lookup method returns an SSHConfigDict with the options that apply to the host. Keys are lowercased, values are strings, and identityfile is a list, because the option may appear several times. The key_filename parameter of connect accepts that list.

$ python ssh_config.py
{'hostname': 'localhost', 'port': '2222', 'user': 'user7', 'identityfile': ['id_ed25519'], 'identitiesonly': 'yes'}
cf10a4b58d67
uid=1000(user7) gid=1000(user7) groups=1000(user7)

Source

Paramiko documentation

Paramiko changelog

In this article we have worked with SSH and SFTP in Python using the paramiko library. See also Python subprocess, Python FTP, and Python pexpect.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.