Fabric Magic

Today I’m presenting one of my more stupid and useful scripts.

It’s just a skeleton script for executing any script remotely.

Without sanitizing and race condition checking for simplicity, it must called “fabile.py”.


from fabric.api import run, env, put, sudo
import glob
import sys

env.hosts = []
env.user = "my_user"

def setHosts(hosts_list):
	try:
		with open(hosts_list) as f:
		env.hosts = f.read().splitlines()
		f.close()
	except IOerror:
		print "Fichero %s no disponible" % hosts_list
		sys.exit(1)
	env.hosts.sort()
	print env.hosts

def extDev_Show():
	TMP_DIR = run("mktemp -d --tmpdir=/home/%s" % env.user)
	run ("chmod 755 %s" % TMP_DIR)
	try:
		print "Temp dir = %s" % TMP_DIR
		put ("templates/show_ExtDev.sh","%s/" % TMP_DIR, mode=0555)
		sudo("%s/show_ExtDev.sh" % (TMP_DIR))
	except:
		print "Exit by Exception"
	run ("rm -rf %s" % TMP_DIR)


We must already have a file with a list of IPs (or resolvable server names) and sudo permissions for executing that script as “my-user” in those servers.

A temporary directory is created in the home directory of that user on that server (later removed) because some servers restrict executing from temporary filesystem like /tmp. The script “show_ExtDev.sh” it’s just a simple one echoing some network configuration (interfaces, routing tables, fw rules,…) just change it with whatever you want do (like updating a password, creating an account in multiple servers, installing or updating an agent,…).

And that’s all, just call fabric and execute that script in all of them:

fab setHosts:ip_list.txt extDev_Show