G
GuideDevOps
Lesson 10 of 15

Fabric & Paramiko

Part of the Python for DevOps tutorial series.

When you need to automate tasks across multiple remote servers via SSH, Python's Paramiko and Fabric libraries are the best tools for the job.

1. Paramiko (The Low-Level Library)

Paramiko is the foundational library for SSH in Python. It's powerful but can be verbose.

Basic SSH Connection

Action:

import paramiko
 
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
# Example: Connecting to a remote server
client.connect(hostname='10.0.1.42', username='ubuntu', key_filename='~/.ssh/id_rsa')
 
stdin, stdout, stderr = client.exec_command('uptime')
print(f"Server Uptime: {stdout.read().decode().strip()}")
 
client.close()

Result:

Server Uptime: 14:02:45 up 12 days, 3:14, 1 user, load average: 0.05, 0.02, 0.01

2. Fabric (The High-Level Wrapper)

Fabric is built on top of Paramiko and provides a much cleaner, more Pythonic API for common DevOps tasks like running commands and transferring files.

Running Commands

Action:

from fabric import Connection
 
# Simple one-liner for remote execution
c = Connection('10.0.1.42', user='ubuntu')
result = c.run('ls /var/log/nginx', hide=True)
 
print(f"Status: {result.exited}")
print(f"Files found:\n{result.stdout.strip()}")

Result:

Status: 0
Files found:
access.log
error.log

File Transfers (Put and Get)

Action:

from fabric import Connection
 
with Connection('10.0.1.42', user='ubuntu') as c:
    # Upload a local config file to the remote server
    c.put('nginx.conf', '/tmp/nginx.conf')
    print("Upload complete.")
    
    # Download a remote log file to your local machine
    c.get('/var/log/syslog', 'remote-syslog.log')
    print("Download complete.")

Result:

Upload complete.
Download complete.

3. DevOps Use Case: Restarting a Service

A common DevOps task is restarting a service across a pool of servers.

Action:

from fabric import Connection
 
servers = ['10.0.1.1', '10.0.1.2']
 
for host in servers:
    with Connection(host, user='admin') as c:
        print(f"Restarting Nginx on {host}...")
        c.sudo('systemctl restart nginx')

Result:

Restarting Nginx on 10.0.1.1...
Restarting Nginx on 10.0.1.2...

Summary

  • Use Paramiko if you need total control over the SSH protocol.
  • Use Fabric for everyday automation, deployment scripts, and file transfers.
  • Install with pip install fabric (this will install Paramiko automatically).
  • Fabric's run() returns a Result object containing stdout, stderr, and exited.