©2019 by technophilia.io.

  • richardpinto87

Copy of Grab server stats remotely? How about Python's Fabric?

What if you need to automate the process of running various kinda commands on remote servers. It may be some mundane, repetitive tasks that need to run daily or pre, post-deploy steps.

Some of the possible ways to Automate this

* Running commands via a shell or expect script

* Ansible or any Config Management Tool

* Python's 'Fabric' module which in-turn uses modules like 'Paramiko' - We are gonna use this one baby!

Current Functionality and code excerpt

Installed and configured python's fabric on a Centos 7 VM as I faced difficulty using fabric on Mac.

Wrote a fabfile(default config/python script used by fabric) containing a task which runs the necessary commands on the destination hosts and displays the output to stdout.

The destination hosts are defined as json objects in a json file my_roles.json which is referenced within a method in the fabfile and stored as a dictionary(env.roledefs - fab specific variable). Any new host additions would involve only modifying the json file without editing the code.

Installing fabric in Centos 7

install fabric module

# yum install fabric -y NOTE: EPEL yum repo is required if not already present.

# yum install epel-release -y

Current fabfile (fapfile.py)

from fabric.api import * from fabric.contrib.files import * import getpass import json def load_roles(): with open('my_roles.json') as f: env.roledefs = json.load(f) load_roles() env.user = raw_input('Enter SSH User:') env.password = getpass.getpass('Enter SSH Password:') def run_commands(): run('ls -al') sudo("fdisk -l", pty=False)

Define the my_roles.json file containing the host entries. Ensure that the file is in the same directory as the fabfile.

Ensure that you are in the same directory as the fabfile, and then run the 'fab' command to gather stats of the required servers


    "es": [ "", "" ]

run fab command

fab -R es run_commands

The -R switch for the 'fab' command specifies the role for which the following task must run. The roles are defined in the json and loaded when the 'load_roles()' method defined in the fabfile is called.

Note that sudo commands run without the need to manually enter the sudo password again. The fabfile script just takes the 'SSH' username and password as inputs, which in our environment, are also the sudo credentials(for most users atleast). This approach can be used to run application pre and post deployment tasks or run custom scripts remotely.