IC Improve Code Recipes

Recipe 10.5 · Python

SFTP with SSH.NET

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Partners exchange files over SFTP. The integration code usually connects with a password stored in configuration, accepts whatever host key the server presents, downloads files directly to their final names, and leaves half-uploaded files on the server when the network drops. The plain FTP code it replaced, built on FtpWebRequest, was worse: that class is marked obsolete in modern .NET.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

There is no host key check, so a machine in the middle can impersonate the server. The listing includes . and .. and any file still being written by the partner. And f.Name from a remote server is used as a local path without validation.

Requirements: Python 3.12+. Install: pip install paramiko · Needs at run time: an SFTP server. The module loads without them; calling the code does not work without them.

Python SFTP download loop with password auth and no host-key check (p218_r10_5_sftp_download_no_host_key_before.py)
"""SFTP download loop with password auth and no host-key check

Source: ImproveCode, Chapter 10, Recipe 10.5 "SFTP with SSH.NET"
Section: The way it's often written
Book page: 218  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SSH.NET SftpClient -> paramiko; AutoAddPolicy mirrors SSH.NET's default of
trusting any host key. Downloads directly into the final local file.
"""

import os

import paramiko


def download_outbound(host: str, user: str, password: str, local: str) -> None:
    with paramiko.SSHClient() as ssh:
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, username=user, password=password)
        with ssh.open_sftp() as sftp:
            for f in sftp.listdir_attr("/outbound"):
                with open(os.path.join(local, f.filename), "wb") as fs:
                    sftp.getfo(f"/outbound/{f.filename}", fs)

The improved recipe

The transfer class authenticates with a private key, verifies the server's host key against a pinned SHA-256 fingerprint, uploads to a temporary name and renames, and downloads through SafePath and AtomicFile from the earlier recipes.

NuGet package: SSH.NET (namespace Renci.SshNet). The listing uses the async API of recent releases and was built against version 2026.0.1.

Requirements: Python 3.12+. Install: pip install paramiko · Needs at run time: an SFTP server. The module loads without them; calling the code does not work without them.

Python SFTP upload/download with pinned host key, .part uploads and atomic downloads (p219_r10_5_sftp_transfer_pinned_host_key.py)
"""SFTP upload/download with pinned host key, .part uploads and atomic downloads

Source: ImproveCode, Chapter 10, Recipe 10.5 "SFTP with SSH.NET"
Section: The improved recipe
Book page: 219-221  -- original C# listing
Converted from C# to Python.
SSH.NET -> paramiko (blocking; async methods wrap it in asyncio.to_thread where
it matters). Host key is checked against the SHA256 fingerprint via a custom
MissingHostKeyPolicy. SafePath/AtomicFile come from p205/p208.
"""

from __future__ import annotations

import asyncio
import base64
import hashlib
import os
import stat
from dataclasses import dataclass
from typing import BinaryIO

import paramiko

from p205_r10_1_safe_path_combine_and_filename import try_combine
from p208_r10_2_atomic_file_write_temp_rename import write_async


@dataclass
class SftpSettings:
    host: str = "localhost"
    port: int = 22
    user_name: str = ""
    private_key_path: str | None = None
    private_key_passphrase: str | None = None
    password: str | None = None
    host_key_sha256: str = ""
    timeout_seconds: int = 30


class _PinnedHostKeyPolicy(paramiko.MissingHostKeyPolicy):
    def __init__(self, expected: str) -> None:
        self._expected = expected

    def missing_host_key(self, client: paramiko.SSHClient,
                         hostname: str, key: paramiko.PKey) -> None:
        digest = hashlib.sha256(key.asbytes()).digest()
        fingerprint = base64.b64encode(digest).decode().rstrip("=")
        if fingerprint != self._expected:
            raise paramiko.SSHException(
                f"Host key for {hostname} does not match the pinned value.")


class SftpTransfer:
    def __init__(self, settings: SftpSettings) -> None:
        if settings is None:
            raise ValueError("settings is required")
        if not settings.host_key_sha256 or not settings.host_key_sha256.strip():
            raise ValueError("host_key_sha256 must not be null or whitespace")
        self._settings = settings

    async def upload_async(self, local_path: str, remote_folder: str) -> None:
        await asyncio.to_thread(self._upload, local_path, remote_folder)

    def _upload(self, local_path: str, remote_folder: str) -> None:
        with self._create_client() as ssh, ssh.open_sftp() as client:
            name = os.path.basename(local_path)
            final = f"{remote_folder.rstrip('/')}/{name}"
            partial = final + ".part"

            with open(local_path, "rb") as input:
                client.putfo(input, partial)
            try:
                client.stat(final)
                client.remove(final)
            except FileNotFoundError:
                pass
            client.rename(partial, final)

    async def download_all_async(
        self, remote_folder: str, local_folder: str,
        delete_after_download: bool,
    ) -> list[str]:
        ssh = await asyncio.to_thread(self._create_client)
        try:
            client = ssh.open_sftp()
            downloaded: list[str] = []
            for file in client.listdir_attr(remote_folder):
                local = try_combine(local_folder, file.filename)
                if (not stat.S_ISREG(file.st_mode or 0)
                        or file.filename.endswith(".part")
                        or local is None):
                    continue

                full_name = f"{remote_folder.rstrip('/')}/{file.filename}"

                async def _download(stream: BinaryIO, src: str = full_name) -> None:
                    await asyncio.to_thread(client.getfo, src, stream)

                await write_async(local, _download)
                downloaded.append(local)

                if delete_after_download:
                    await asyncio.to_thread(client.remove, full_name)
            client.close()
            return downloaded
        finally:
            ssh.close()

    def _create_client(self) -> paramiko.SSHClient:
        s = self._settings
        pkey: paramiko.PKey | None = None
        if s.private_key_path:
            pkey = paramiko.PKey.from_path(
                s.private_key_path,
                passphrase=(s.private_key_passphrase.encode()
                            if s.private_key_passphrase else None))

        expected = s.host_key_sha256.replace("SHA256:", "")
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(_PinnedHostKeyPolicy(expected))
        client.connect(
            s.host, port=s.port, username=s.user_name,
            pkey=pkey, password=s.password or None,
            timeout=s.timeout_seconds,
            look_for_keys=False, allow_agent=False,
        )
        return client

How it works

The host key check is the line most SFTP code leaves out. SSH.NET raises HostKeyReceived during the handshake, and the connection fails unless the handler sets CanTrust to true. The listing compares the server's SHA-256 fingerprint with the one in configuration. You get the fingerprint once, out of band, from the partner or with ssh-keyscan host | ssh-keygen -lf -, and it looks like SHA256:ohD8VZ.... The code accepts it with or without the prefix. When a partner rotates their key, the connection fails loudly until you update the setting, which is exactly what you want.

Private key authentication is preferred over passwords. The key file stays on the server with file permissions limited to the service account, and if a passphrase is used, it comes from a secret store.

Uploads go to name.part and are renamed when complete, so the partner's pickup job never sees a partial file. The existing file is deleted first, because a plain SFTP rename fails if the target exists on many servers. Downloads skip directories, the . and .. entries (they are not regular files), and .part files a partner might be writing. Each remote name passes through SafePath.TryCombine before it touches the local disk, since a hostile or broken server could send any name. AtomicFile means a dropped connection leaves no partial local file.

Variations and pitfalls

  • Plain FTP and FTPS. FtpWebRequest and WebClient are obsolete. If a partner only offers FTP or FTPS, use the FluentFTP package, require TLS (FtpEncryptionMode.Explicit) and validate the certificate. Push hard for SFTP.
  • Delete or archive. Some partners prefer you move downloaded files to an archive folder with RenameFileAsync instead of deleting them.
  • Idempotency. Even with care, a crash between download and delete means the next run downloads the file again. Record processed file names and sizes in a table, and skip files you have seen.
  • Retries. Wrap the call in the retry policy from Chapter 5, retrying only SshConnectionException, SocketException and timeouts, never authentication failures.