Skip to content

Instantly share code, notes, and snippets.

@meoow
Created August 4, 2014 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meoow/132d08eb3ec348b34ffd to your computer and use it in GitHub Desktop.
Save meoow/132d08eb3ec348b34ffd to your computer and use it in GitHub Desktop.
Update/delete entries in system hosts file by a hosts file or URL
#!/usr/bin/env python2.7
import re
import os, os.path
import sys
import urllib2
from contextlib import closing
USAGE = "{0} hosts".format(sys.argv[0])
class Hosts(object):
ipmatch = re.compile(r'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){3}$')
if sys.platform == 'win32':
hostsLocation = \
os.sep.join((os.environ['windir'], r'system32\drivers\etc\hosts'))
else:
hostsLocation = '/etc/hosts'
def __init__(self):
self.hosts, self.unkownLines = \
self.parseHosts(self.hostsLocation)
def update(self, hostsfile):
newhosts, _ = self.parseHosts(hostsfile)
self.hosts.update(newhosts)
def parseHosts(self, hostsfile):
hosts = {}
unkownLines = []
if not os.path.exists(hostsfile):
if hostsfile.startswith('http'):
gopen = urllib2.urlopen
else:
return hosts, unkownLines
else:
gopen = open
with closing(gopen(hostsfile)) as f:
for l in f:
l = l.strip()
if not l or l.startswith('#'):
continue
ip, domain = l.split()[:2]
if self.ipmatch.search(ip):
hosts[domain] = ip
else:
unkownLines.append(l)
return hosts, unkownLines
def writeHosts(self):
if os.path.exists(self.hostsLocation) and \
not os.access(self.hostsLocation, os.W_OK):
raise SystemExit(\
'ERROR: Do not have write permission for {0}'.format(\
self.hostsLocation))
with open(self.hostsLocation, 'w') as w:
for line in self.unkownLines:
w.write('{0}\n'.format(line))
w.write('\n')
for domain,ip in self.hosts.iteritems():
w.write('{0} {1}\n'.format(ip, domain))
def deleteHosts(self, domainList):
for i in domainList:
if i in self.hosts:
del self.hosts[i]
def deleteHostsFromFile(self, hostsfile):
hosts, _ = self.parseHosts(hostsfile)
self.deleteHosts(hosts.keys())
if __name__ == '__main__':
if len(sys.argv) < 2:
print USAGE
raise SystemExit
hosts = Hosts()
#hosts.deleteHostsFromFile(sys.argv[1])
hosts.update(sys.argv[1])
hosts.writeHosts()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment