Skip to content

Instantly share code, notes, and snippets.

@smeans
Last active July 5, 2021 06:48
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 smeans/5b7f09e6e67694fc74eab4b91714a32f to your computer and use it in GitHub Desktop.
Save smeans/5b7f09e6e67694fc74eab4b91714a32f to your computer and use it in GitHub Desktop.
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