Skip to content

Instantly share code, notes, and snippets.

@orymate
Created January 24, 2016 19:56
Show Gist options
  • Save orymate/4ac377800c52e5978a44 to your computer and use it in GitHub Desktop.
Save orymate/4ac377800c52e5978a44 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from optparse import OptionParser
from subprocess import check_call
def main():
parser = OptionParser("usage: %prog [options] fqdn")
parser.add_option("-d", "--dry-run",
action="store_true", dest="dry_run")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
fqdn = args[0]
host = fqdn.split(".")[0]
hostsfile = "/etc/hosts"
with open(hostsfile, "r") as f:
hosts = f.readlines()
if options.dry_run:
hostsfile = "/dev/stdout"
with open(hostsfile, "w") as f:
for line in hosts:
split = line.split()
if len(split) == 0 or split[0] != "127.0.1.1":
f.write(line)
f.write("127.0.1.1 {fqdn} {host}\n".format(host=host, fqdn=fqdn))
if options.dry_run:
return
with open("/etc/hostname", "w") as f:
f.write("{host}\n".format(host=host))
check_call(["hostname", "-F", "/etc/hostname"])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment