Python fabric

Basic usage of python fabric.


$ sudo pip install fabric

$ which fab
/usr/local/bin/fab (Mac)

Run commands directly from command line

$ fab -H -u root -p root123 -- 'uname -a'
# -H => The remote host to run command on, same as --hosts
# -u => The ssh username of the remote host, same as --user
# -p => The ssh password of the remote host, same as --password
# fab -h => list all available options and args

Run fabfile and passing in command line arguments

  • Define
from fabric.api import run, env, local
env.hosts = []
env.user = "root"
env.password = "root123"

def show_ros_info():
    '''show remote os info'''
    run("uname -a")

def show_los_info():
    '''show local os info'''
    local("uname -a")

# an example to add swap for remote os
def add_swap(swapfile="/opt/swap", swapsize_mb=512):
    count = 1024 * int(swapsize_mb)
    run("free -m")
    run("dd if=/dev/zero of=%s bs=1024 count=%s" % (swapfile, str(count)))
    run("mkswap %s" % swapfile)
    run("chown root:root %s" % swapfile)
    run("chmod 0600 %s" % swapfile)
    run("swapon %s" % swapfile)
    run("echo %s swap swap defaults 0 0 >> /etc/fstab" % swapfile)
    run("free -m")
  • Run above fabfile
$ fab show_ros_info:hosts=

$ fab show_los_info:host=

$ fab add_swap:hosts=

$ fab add_swap:swapsize_mb=256

$ fab add_swap:hosts=,swapfile=/tmp/test,swapsize_mb=1024

$ fab -f ...
$ fab --fabfile ...

# 1) The option 'hosts' (or host/role/roles) are special keyword arguments for
#    per-task configuration; if absent, the env.hosts will be used.
# 2) The function arguments should be passed after the colon(:) and separated
#    with comma(,) and match definition; but optional for keyword arguments.
# 3) If the is not named, such as instead, then
#    the file must be explicitly provided using the "-f" or "--fabfile" option.

See Fabric’s documentation for more details.