PIP-Talk - Week 39

Every week going forward I plan to write a little about interesting modules/libraries available for Python.

The topic for this week is: Fabric

Fabric is a high level Python (2.7, 3.4+) library designed to execute shell commands remotely over SSH, yielding useful Python objects in return.

The most basic use of Fabric is to execute a shell command on a remote system via SSH, then (optionally) interrogate the result. By default, the remote program’s output is printed directly to your terminal, and captured

fab - command line utility

Fabric also provides a command line utility (fab), which reads its configuration from a file named fabfile.py in directory from which it is run. A typical fabfile contains one or more functions to be executed on a group of remote hosts.

The following example provides functions to start/stop and check status for a Apache server.

from fabric.api import run, env

# Set the hosts name
env.hosts = ''

# Define function to start Apache server
def start_apache():
    run('sudo systemctl start apache2')
    print('Apache server is started.')

# Define function to stop Apache server
def stop_apache():
    run('sudo systemctl stop apache2')
    print('Apache server is stopped.')

# Define function to check the status of Apache server
def status_apache():
    run('sudo systemctl status apache2')

Run the following command from the terminal to start the apache server with the fab command.

fab --user-fahmida --password=12345 start_apache

Whats the use case, what problem does it solve ?

Here is a couple of usecases for Fabric.

  • Misc devops task on a build server (copy, remove files etc)
  • Sync/copy files between servers
  • Start/stop deamons on a remote server or a cluster
  • Maintaince jobs (for a database, mailserver, git, etc)
  • Fetch diagnostics (cpu, diskspace, etc) for remote server or a cluster
  • upload/download files to a remote server or a cluster
  • Execute optional script/program on remote host/hosts

Example code

Here is a simple example code that will check the uptime for several servers.

#!/usr/bin/env python

from fabric.api import env, run

env.hosts = [ '', 'localhost' ]

def uptime():



pip install fabric"