Running remote commands over SSH with Python Fabric

Fabric is a Python library for running shell commands on remote machines over SSH. It wraps Paramiko (SSH) and Invoke (task running), so you can script deploys and admin chores in Python instead of shell, and run them against one host or many.
This post uses Fabric 3.2. Fabric 2 was a rewrite, and code written for Fabric 1 (from fabric.api import run, env) doesn’t run on 2.x or 3.x.
Prerequisites
Section titled “Prerequisites”You need a server you can already reach with ssh user@host using a key. If you don’t have a key yet:
ssh-keygen -t ed25519ssh-copy-id user@your_serverssh user@your_server # should log in without a password promptFabric reads ~/.ssh/config, so host aliases, users, ports and IdentityFile entries defined there also apply to Fabric.
pip install fabricA plain script with Connection
Section titled “A plain script with Connection”A Connection is one SSH session to one host. run() executes a command and returns a Result with stdout, stderr, exited and ok:
from fabric import Connection
with Connection(host="your_server", user="user") as c: result = c.run("uname -a", hide=True) print(result.stdout.strip())
# A non-zero exit code raises UnexpectedExit unless you pass warn=True. check = c.run("test -d /srv/app", warn=True, hide=True) print("app dir exists" if check.ok else "app dir missing")python remote_info.pyhide=True stops Fabric from echoing the remote output to your terminal. You still get it in result.stdout.
Some other Connection methods you’ll use often:
c.sudo("systemctl restart nginx") # run as root via sudoc.put("dist/app.tar.gz", "/tmp/app.tar.gz") # upload a filec.get("/var/log/nginx/error.log", "error.log") # download a file
with c.cd("/srv/app"): c.run("git pull") # runs as: cd /srv/app && git pullc.cd() only affects commands run inside the with block. Each run() is a separate shell, so c.run("cd /srv/app") on its own does nothing for the next command.
Tasks with fab
Section titled “Tasks with fab”For repeatable operations, put tasks in a fabfile.py and run them with the fab command. Each task receives a Connection as its first argument when you pass a host with -H:
from fabric import task
@taskdef update(c): c.sudo("apt-get update")
@taskdef upgrade(c): c.sudo("apt-get upgrade -y")
@taskdef install_package(c, package_name): c.sudo(f"apt-get install -y {package_name}")
@taskdef disk_usage(c): result = c.run("df -h /", hide=True) print(f"{c.host}:\n{result.stdout.strip()}")fab --listfab -H user@your_server updatefab -H user@your_server install-package --package-name nginxfab -H web1,web2,web3 disk-usageFabric turns underscores into dashes, so install_package becomes install-package and its argument becomes --package-name. With a comma-separated -H list, the task runs once per host, one after another.
sudo passwords
Section titled “sudo passwords”If sudo on the server asks for a password, use c.sudo() rather than c.run("sudo ..."). c.sudo() answers the password prompt for you, while run("sudo ...") just waits for input. Supply the password at runtime instead of hard-coding it:
fab -H user@your_server --prompt-for-sudo-password updateFurther reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)