Skip to content

Instantly share code, notes, and snippets.

@smeans
Last active Jul 5, 2021
Embed
What would you like to do?
Command line tool for toggling hosts file records
#/usr/bin/env python
# hostmod.py -- Command line tool for toggling hosts file records
#
# Written in 2020 by W. Scott Means (smeans@gmail.com)
# To the extent possible under law, the author has dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication along with
# this software. If not, see <https://creativecommons.org/publicdomain/zero/1.0/>.
import sys
import re
import argparse
hostpaths = {'win32': '/windows/system32/drivers/etc/hosts', 'linux': '/etc/hosts'}
line_endings = {'win32': '\n', 'linux': '\n'}
parser = argparse.ArgumentParser(description='toggles specified hostname in system hosts file')
parser.add_argument('switch', help='action to take', choices=['on', 'off', 'toggle', 'list'])
parser.add_argument('host', help='host name to switch', nargs='?')
parser.add_argument('-p', '--path', default=hostpaths[sys.platform])
parser.add_argument('-u', '--update', help='update hosts file in place', action='store_true')
parser.add_argument('-v', '--verbose', help='verbose output', action='store_true')
args = parser.parse_args()
sle = line_endings[sys.platform]
with open(args.path, 'r') as f:
oldfile = f.read()
if args.switch == 'list':
print(oldfile)
sys.exit(0)
lines = oldfile.split(sle)
res = re.compile(r'(\s+)')
newfile = ''
found = False
nla = []
for line in lines:
la = res.split(line.strip())
if len(la) > 2 and la[2] == args.host:
found = True
shouldComment = la[0][0] != '#' if args.switch == 'toggle' else args.switch != 'on'
if shouldComment:
if la[0][0] != '#':
la[0] = '#' + la[0]
elif la[0][0] == '#':
la[0] = la[0][1:]
nla.append(''.join(la))
newfile = sle.join(nla)
if not found:
print('hostmod: host %s not found' % args.host)
if newfile == oldfile:
print('hostmod: no changes made', file=sys.stderr)
elif args.update:
with open(args.path, 'w') as f:
f.write(newfile)
if not args.update or args.verbose:
print(newfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment