#!/usr/bin/env python2 # this script add aliases to /etc/hosts import sys, re if len(sys.argv) < 2 or len(sys.argv) > 3: sys.exit(1) host = sys.argv[1] alias = sys.argv[2] if len(sys.argv) == 3 else "localhost" if host == "localhost" or host == alias: sys.exit(0) print "Adding host {} as an alias of {}".format(host, alias) with open("/etc/hosts", "r+") as f: buf = re.sub(r"\\b{}\\b".format(alias), "{}\\t{}".format(alias, host), f.read(), 1) f.seek(0) f.write(buf)