Skip to content

Instantly share code, notes, and snippets.

@teroka
Created September 28, 2013 13:10
Show Gist options
  • Save teroka/6741930 to your computer and use it in GitHub Desktop.
Save teroka/6741930 to your computer and use it in GitHub Desktop.
Glue to keep specific entries up to date in /etc/hosts
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Superglue to keep /etc/hosts up-to-date of given entries.
If the entry doesn't exists, we won't add it. We only keep
the EXISTING entries updated.
* depends on python-dnspython
'''
import dns.resolver
import sys
# set the hosts you want to keep updated in the hosts file
hosts = [ 'www.google.com', 'www.gmail.com' ]
# set the dns resolver(s) you want to use
set_dns = [ '8.8.8.8' ]
##########################################################
resolver = dns.resolver.Resolver()
resolver.nameservers = set_dns
resolver.timeout = 5
local_hosts = '/etc/hosts'
results = {}
for host in hosts:
try:
answers = resolver.query(host, 'A')
ips = []
for data in answers:
ips.append(data.address)
# Sort the addresses as we only take the first ONE, even if there's
# multiple given by the resolver. Sorting's there to recude the amount
# of unnecessary editing due RR.
results[host] = sorted(ips)
except dns.resolver.NXDOMAIN:
sys.stderr.write('Domain not found: %s\n' % host)
sys.exit(1)
except dns.resolver.Timeout:
sys.stderr.write('Timeout while trying to resolv: %s\n' % host)
sys.exit(1)
except dns.exception.DNSException:
sys.stderr.write('Unhandled exception\n')
sys.exit(1)
# read in the hosts file to hosts_file list, strip \n and split on whitespace
hosts_file = [line.strip().split() for line in open(local_hosts, 'r')]
change_detected = None
for entry in hosts_file:
try:
for host in results:
if entry[1] == host and entry[0] != results[host][0]:
print '%s address changed from %s to %s' % (host, entry[0],
results[host][0] )
entry[0] = results[host][0]
change_detected = True
except IndexError:
pass
if change_detected:
# Write the hosts file back if we've spotted a change
with open(local_hosts,'w') as filu:
filu.write('\n'.join(' '.join(row) for row in hosts_file))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment