How to setup Python fabric on CentOS

Python Fabric is a very good automation tool specially when you have access to a Linux machine via SSH.

This example was tested on CentOS 6.6 docker image:
(Note: You will need epel repository configured on your machine, if its a centos box you can install it by typing: yum install epel-release
So lets start configuring Fabric:

[[email protected] /]# yum search fabric
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base:
* epel:
* extras:
* updates:
fabric.noarch : A simple Pythonic remote deployment tool
[[email protected] /]# yum install fabric

This should install fabric for you.

Now if you haven’t setup SSH key pair on your remote machine that you would like to control via Fabric, you can run the following on your current machine to create key pair, once done copy the public part of the key to authorized_keys file on the remote server:

[[email protected] /]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/

Now for this example I have created another docker instance that is running openssh-server and is configured to accept keys. I have already copied the public key to the other docker instance, so I can log into the second docker instance without providing the password. So lets write the fabfile and run remote commands using Fabric:

[[email protected] ~]# cat
from fabric.api import *

def hostname():
[[email protected] ~]# fab -H hostname
[] Executing task 'hostname'
[] run: hostname
[] out: edf6ac0f4d24
[] out:
Disconnecting from done.

In the above case is my second docker instance. Lets try to run another command remotely … how about getting the contents of hosts file. So all we need to do is to add another function in the fab file and call the function for the desired host:

[[email protected] ~]# cat
from fabric.api import *

def hostname():

def hostsfile():
run("cat /etc/hosts")
[[email protected] ~]# fab -H hostsfile
[] Executing task 'hostsfile'
[] run: cat /etc/hosts
[] out: edf6ac0f4d24
[] out: localhost
[] out: ::1 localhost ip6-localhost ip6-loopback
[] out: fe00::0 ip6-localnet
[] out: ff00::0 ip6-mcastprefix
[] out: ff02::1 ip6-allnodes
[] out: ff02::2 ip6-allrouters
[] out:
Disconnecting from done.

So fabric is lovely little tool to run remote commands on the server. Ofcourse you can use SSH to do all these tasks, but fabric provides you a way of managing scripts (for remote servers) in an efficient and reliable manner.

Leave a Reply

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