Skip to main content

Command Palette

Search for a command to run...

Day 100: Fabric in Python

Remote SSH Execution with Python's Fabric in DevOps

Published
2 min read
Day 100: Fabric in Python

Today, you’ll learn how to use Fabric, a powerful Python library for automating remote command execution over SSH. This is extremely useful for deployments, server maintenance, and configuration tasks in DevOps workflows.


🧠 What is Fabric?

Fabric is a high-level Python library that lets you:

  • SSH into remote servers

  • Run commands and scripts remotely

  • Upload and download files

  • Automate deployment steps

It’s often used as a lightweight alternative to heavy configuration management tools for small-scale tasks.


⚙️ Setup

📦 Install Fabric

uv add fabric

💻 Basic Example — Run Commands on a Remote Server

from fabric import Connection

# Create an SSH connection
c = Connection(
    host="your-server-ip",
    user="your-ssh-username",
    connect_kwargs={
        "key_filename": "/path/to/your/private-key.pem"  # or use "password": "yourpassword"
    },
)

# Run commands remotely
c.run("uname -a")
c.run("uptime")

Output Example:

Linux ip-172-31-45-20 5.15.0-105-generic ...
 14:25:11 up 3 days,  2:03,  2 users,  load average: 0.00, 0.01, 0.05

📁 Upload and Download Files

# Upload a file to the remote server
c.put("local_script.sh", "/tmp/remote_script.sh")

# Download a file from the remote server
c.get("/var/log/syslog", "syslog_backup.log")

⚡ Automating a Deployment

def deploy():
    with Connection(host="your-server-ip", user="ubuntu", connect_kwargs={"key_filename": "~/.ssh/id_rsa"}) as c:
        c.run("git clone https://github.com/user/app.git || cd app && git pull")
        c.run("docker compose down && docker compose up -d --build")

deploy()

💡 Use Cases in DevOps

  • Quick patch updates on multiple servers

  • Deploying code directly over SSH

  • Restarting services or containers

  • Gathering system logs from servers

  • Executing ad-hoc maintenance scripts

DevOps overview as a beginner

Part 1 of 50

Sharing my journey of learning DevOps as a beginner — covering essential tools, cloud setup, CI/CD, Docker, monitoring, and more, step by step with practical examples.