Paramiko in Python Guide: Secure SSH Command Execution and SFTP File Transfer

Python tutorial - IT technology blog
Python tutorial - IT technology blog

2:15 AM and a Disk Exhaustion Incident Across 10 Servers

The clock struck 2:15 AM when PagerDuty started screaming. A 10-node database log cluster simultaneously hit 98% disk capacity. The payment gateway was dropping over 300 transactions per minute. Angry customer complaints began flooding support channels. Jolting awake with burning eyes, I rushed to open my laptop.

To avoid manually SSHing into every single node, I ran a quick Python script using subprocess.Popen(["ssh", ...]) to bulk-purge the logs. But the worst-case scenario struck: the terminal froze completely.

The first node didn’t have its host key saved. OpenSSH paused, waiting for interactive verification: The authenticity of host... can't be established. The subprocess hung on the I/O stream indefinitely. With the script frozen, log files continued ballooning, causing two nodes to crash shortly after. It was an expensive lesson in using the wrong automation tools.

Why Invoking OpenSSH via Subprocess Fails

Calling the ssh binary directly through Python might seem convenient, but it carries severe production risks:

  • Hangs on Host Key Verification: OpenSSH defaults to requiring TTY interaction when connecting to an unknown host. Subprocess cannot capture or respond to this prompt, plunging the process into a deadlock.
  • Prone to Pipe Buffer Overflows: Linux pipe buffers are typically limited to 64KB. If a remote command outputs a massive volume of data, it fills the buffer, halting the process if the program hasn’t read from it in time.
  • Sensitive Data Exposure: Passing passwords or secrets via command-line arguments exposes them to trivial snooping through ps aux or shell history files.
  • Unreliable SFTP Operations: Using CLI-based scp makes tracking precise transfer progress difficult and fails to catch granular network exceptions during intermittent drops.

Comparing SSH Automation Approaches in Python

Option 1: Sticking with Subprocess via sshpass or pexpect

Many developers reach for quick hacks like installing sshpass or using pexpect to bypass password and host key prompts:

import subprocess

# Quick and dirty workaround: Prone to hangs, severe security risks
cmd = "sshpass -p 'secret' ssh -o StrictHostKeyChecking=no [email protected] 'df -h'"
subprocess.run(cmd, shell=True)

While this snippet runs immediately, it exposes cleartext credentials in the OS process table. Furthermore, it introduces hard dependencies on external system binaries.

Option 2: Using Ansible or Fabric

Fabric and Ansible excel at large-scale infrastructure orchestration. However, if you only need to integrate SSH/SFTP capabilities into a lightweight backend worker, pulling in the entire footprint of Ansible is unnecessary overkill.

Complete SSH and SFTP Control with Paramiko

Paramiko is a pure-Python implementation of the SSHv2 protocol. It grants low-level control over individual sockets, authentication keys, and SFTP streams without relying on external system utilities.

1. Library Installation

Install the package via pip:

pip install paramiko

2. Executing Remote Commands Safely in Production

The following script configures explicit timeouts and correctly consumes stdout/stderr streams to eliminate connection hangs:

import paramiko
import socket

def execute_remote_command(hostname, username, key_path, command):
    client = paramiko.SSHClient()
    
    # Automatically add missing host keys to the session cache
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # Load private key (supports RSA, Ed25519)
        pkey = paramiko.RSAKey.from_private_key_file(key_path)
        
        print(f"[*] Connecting to {hostname}...")
        client.connect(
            hostname=hostname,
            port=22,
            username=username,
            pkey=pkey,
            timeout=10,        # TCP connection timeout (seconds)
            banner_timeout=15   # SSH banner exchange timeout
        )
        
        print(f"[*] Executing command: {command}")
        stdin, stdout, stderr = client.exec_command(command, timeout=30)
        
        # Close stdin to indicate the client will send no further data
        stdin.close()
        
        # Retrieve exit status and output streams
        exit_status = stdout.channel.recv_exit_status()
        out = stdout.read().decode('utf-8', errors='replace')
        err = stderr.read().decode('utf-8', errors='replace')
        
        if exit_status == 0:
            print("[+] Command output:\n" + out)
        else:
            print(f"[-] Command failed (Exit code {exit_status}):\n" + err)
            
        return exit_status, out, err
        
    except (paramiko.SSHException, socket.timeout, Exception) as e:
        print(f"[!] Connection error to {hostname}: {str(e)}")
        return -1, "", str(e)
    finally:
        client.close()

# Execute emergency log cleanup
execute_remote_command(
    hostname="192.168.1.100",
    username="deployer",
    key_path="/home/ubuntu/.ssh/id_rsa",
    command="find /var/log/apps -type f -name '*.log' -mtime +3 -delete && df -h /"
)

3. Transferring Large Files Using SFTPClient

Rather than repeatedly re-establishing sessions, maintain a persistent Transport channel and attach a callback to monitor upload progress:

import os
import paramiko

def progress_callback(transferred, total):
    percent = (transferred / total) * 100
    print(f"\rProgress: {transferred}/{total} bytes ({percent:.1f}%)", end="")

def upload_file_sftp(hostname, username, key_path, local_file, remote_file):
    transport = None
    try:
        pkey = paramiko.RSAKey.from_private_key_file(key_path)
        transport = paramiko.Transport((hostname, 22))
        transport.connect(username=username, pkey=pkey)
        
        sftp = paramiko.SFTPClient.from_transport(transport)
        
        print(f"[*] Uploading {local_file} to {remote_file}...")
        sftp.put(local_file, remote_file, callback=progress_callback)
        print("\n[+] Upload complete!")
        
        # Verify file size on remote host
        remote_stat = sftp.stat(remote_file)
        print(f"[+] Actual remote file size: {remote_stat.st_size} bytes")
        
        sftp.close()
    except Exception as e:
        print(f"\n[!] SFTP Error: {str(e)}")
    finally:
        if transport:
            transport.close()

upload_file_sftp(
    hostname="192.168.1.100",
    username="deployer",
    key_path="/home/ubuntu/.ssh/id_rsa",
    local_file="patch_v1.2.tar.gz",
    remote_file="/opt/patches/patch_v1.2.tar.gz"
)

4. Important Caveat: Avoiding Buffer Deadlocks

When running commands that dump tens of thousands of log lines—such as journalctl -xe—the 64KB pipe buffer for stdout fills up rapidly. Once saturated, the remote server blocks further writing until the client drains the buffer. If your script waits for command completion before invoking stdout.read(), both ends deadlock indefinitely.

The solution: Stream and read data in chunks, or redirect massive output directly to a temporary file on the remote server prior to processing.

Share: