Advertisement
Open Source Projects by Phil Schwartz

Building a Python tool for SSH key generation and distribution

Automating SSH access can remove a great deal of repetitive administration from Linux environments. A small Python utility can create a key pair, record which account owns it, and place the public key in the correct authorized_keys file on approved hosts. The result is quicker onboarding, consistent configuration, and fewer copied-and-pasted keys.

The safest design separates key generation from key distribution. Private keys should remain on the operator’s workstation or a controlled secrets store, while remote machines receive only the public key. This distinction matters for a developer supporting systems across Sydney, Melbourne, Brisbane, or an Australian cloud region, where an accidental private-key upload can create a serious incident.

Python is well suited to the task because it offers mature SSH libraries, clear filesystem APIs, and easy integration with inventory files or internal services. The implementation should still follow the same principles as established Linux utilities: explicit permissions, useful audit records, predictable errors, and no surprise changes to existing accounts.

A practical tool can begin as a command-line program and later gain a configuration file, a dry-run mode, and support for multiple hosts. Reviewing related Python security projects can also provide useful ideas about handling authentication failures, logging, and defensive defaults.

Define the security boundary

Begin by deciding what the program is allowed to do. It may generate an Ed25519 key pair, connect to a host using an already trusted administrator credential, and append one public key to a named user’s account. It should not silently create remote users, overwrite authorized_keys, disable host-key checking, or transmit private material.

Ed25519 is a sensible default for modern OpenSSH installations because it produces compact keys with strong security characteristics. RSA remains useful when compatibility with older appliances is required; in that case, use at least 3072 bits. Do not invent a cryptographic format yourself. Let OpenSSH or a maintained library handle key encoding and signature details.

The interface might accept --user, --host, --port, --key-name, and --identity-file options. Require an explicit confirmation, or offer --dry-run, before changing a remote account. In a business environment subject to the Australian Privacy Principles, keep logs focused on operational metadata rather than recording private keys, passphrases, or unnecessary personal information.

Generate and protect the key pair

The cryptography package provides a direct way to create an Ed25519 key and serialise it in OpenSSH-compatible formats:

from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

def generate_key_pair(directory: Path, name: str):
    directory.mkdir(mode=0o700, parents=True, exist_ok=True)

    private_key = Ed25519PrivateKey.generate()
    private_path = directory / name
    public_path = Path(f"{private_path}.pub")

    private_bytes = private_key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.OpenSSH,
        serialization.NoEncryption(),
    )
    public_bytes = private_key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH,
    )

    private_path.write_bytes(private_bytes)
    public_path.write_bytes(public_bytes + b"\n")
    private_path.chmod(0o600)
    public_path.chmod(0o644)
    return private_path, public_path

For unattended systems, avoid NoEncryption() unless the surrounding storage is already strongly protected. A passphrase-protected private key is safer for a human operator, while a deployment service may need a dedicated secret manager and a tightly restricted runtime identity. On macOS or Linux workstations, also consider whether the operating system’s SSH agent can hold the unlocked key without exposing it to every process.

Use exclusive file creation or a temporary file followed by an atomic rename. That prevents a process interruption from leaving a truncated key. Refuse to overwrite an existing private key unless the operator supplies an explicit replacement flag and the tool first creates a secure backup with restricted permissions.

Validate hosts before connecting

Distribution should use Paramiko or the system’s ssh and ssh-copy-id commands, depending on the required feature set. Paramiko gives Python control over authentication and file operations, but its host-key policy must be configured carefully. Loading the user’s known-hosts file and rejecting unknown keys is safer than automatically accepting every server.

A simplified connection flow looks like this:

import paramiko

def connect(host, username, identity_file, known_hosts):
    client = paramiko.SSHClient()
    client.load_host_keys(str(known_hosts))
    client.set_missing_host_key_policy(paramiko.RejectPolicy())
    client.connect(
        hostname=host,
        username=username,
        key_filename=str(identity_file),
        timeout=15,
        look_for_keys=False,
        allow_agent=False,
    )
    return client

The initial administrator credential might be a separate key, a short-lived certificate, or an interactive password. Avoid embedding credentials in source code, shell history, or a world-readable YAML file. For Australian teams operating across AEST, ACST, and AWST, include UTC timestamps in logs so events remain unambiguous when staff in Perth and Sydney review the same deployment.

Connection failures should distinguish DNS errors, refused connections, authentication failures, host-key mismatches, and remote permission problems. That makes the tool useful during real incidents rather than producing a vague “operation failed” message.

Update authorized_keys safely

Never replace the whole authorized_keys file merely to add one entry. Read the existing file, compare complete public-key lines, and append the new key only when it is absent. Preserve comments and unrelated keys so the operation does not disconnect another administrator or monitoring service.

On the remote host, create .ssh with mode 0700, create authorized_keys with mode 0600, and verify ownership matches the target account. Paramiko’s SFTP interface can perform these operations, although a carefully quoted remote command may be simpler when shell utilities are already available.

Use a marker comment such as managed-by=access-tool host=... to make entries identifiable without recording secrets. A removal command should delete only the exact managed line or fingerprint, never every key belonging to the account. This is especially important for small Australian businesses that may share administration between an internal team and a managed service provider.

A robust implementation should account for concurrent edits. Download the file, calculate the intended result, and use a lock or a remote helper script where possible. If the remote filesystem cannot support safe coordination, report the limitation instead of claiming the change is transactional.

Add inventory, auditing, and lifecycle controls

For several servers, store an inventory containing hostnames, ports, account names, and environment labels. Keep private key paths outside the inventory. An entry might identify web-syd-01 as a production host in a Sydney region while a separate record describes a staging machine in Melbourne. Environment labels help prevent a test key from being distributed to production by mistake.

Record the public-key fingerprint, requesting identity, target host, account, result, and timestamp. A structured JSON log is easier to search than free-form text. Do not log the private key, passphrase, full authentication command, or sensitive connection output. Provide a --list, --revoke, and --rotate workflow so keys have a defined lifetime rather than remaining active indefinitely.

The project can also expose a Python API for other utilities. A compact, focused tool such as Mr Sparkle demonstrates the value of giving a small developer utility a clear purpose and manageable interface. Keep generation, validation, transport, and audit functions separate so each part can be tested independently.

Test the tool before production use

Build tests around temporary directories and disposable virtual machines. Check that private files receive mode 0600, public files receive mode 0644, existing key lines remain unchanged, duplicate distribution is harmless, and an interrupted write does not destroy a previous file. Test malformed public keys and inaccessible home directories as expected failure cases.

For integration testing, use containers or local virtual machines running OpenSSH. Verify host-key rejection, authentication with the generated private key, account ownership, and behaviour when authorized_keys already contains comments or unusual line endings. Run static analysis and dependency checks as part of continuous integration, then pin reviewed library versions.

Before production rollout, start with one non-critical host and a dry-run report. Require explicit host selection, maintain a revocation path, and ensure an operator can recover if the new key is rejected. These controls turn a simple Python script into a dependable SSH access utility suitable for Linux fleets, internal development environments, and the varied connectivity conditions of the Australian market.