How to use Fabric to run command at several servers

Install fabric

Use your software package manager to install it. By instance if you use Fedora just run:

yum install fabric


from __future__ import with_statement
from fabric.api import *
import fabric.contrib

env.user = ‘jramirez’
env.password = ‘YourPassword’

def ntpd_stop():
sudo(‘/sbin/service ntpd stop’)
sudo(‘/sbin/chkconfig ntpd off’)

def ntpd_status():
run(‘/sbin/service ntpd status’)
run(‘/sbin/chkconfig –list ntpd’)

def multiplehosts():
“””Loads a group of hosts from a config file.
hostsfile: name of the group file, one host per line
hostsfile = ‘TEST-nopp.txt’
base_dir = ‘./’
from os.path import join, abspath, expanduser
filename = abspath(expanduser(join(base_dir, hostsfile)))
fhosts = open(filename)
except IOError:
abort(‘file not found: %s’ % filename)

def has_data(line):
“””‘line’ is not commented out and not just whitespace.”””
return line.strip() and not line.startswith(‘#’)

env.hosts = [ line.strip() for line in fhosts
if has_data(line)]

How to apply the change:

fab multiplehosts ntpd_status

With this command you use the multiplehosts function to populate the env.hosts list, that is the one use it by fabric, and the use the ntpd_status function to run some commands.
In fabric there are two basic ways of running commands:

  • run: To run the command with the user privilege
  • sudo: To run the command with root privileges, always depending of sudoers settings


* Set env.user with the user to login
* Set env.password with the user password
* Set hostsfile, inside multiplehosts, to set the file with the list of servers where run the commands

Extra settings:

* You can set env.warn_only = True to continue after errors

Trying it with a single or a few hosts:

fab ntpd_status -H host1,host2…

More information
Fabric official documentation

2 thoughts on “How to use Fabric to run command at several servers

  1. I plan to test and use FUNC, but the certificate part is a problem at the moment when systems can be provisioned without control… but the idea behind it is pretty good

Leave a Reply

Your email address will not be published. Required fields are marked *