Skip to content

Instantly share code, notes, and snippets.

Last active July 5, 2021 06:48
What would you like to do?
Command line tool for toggling hosts file records
#/usr/bin/env python
# -- Command line tool for toggling hosts file records
# Written in 2020 by W. Scott Means (
# 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 <>.
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 =
if args.switch == 'list':
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] ==
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:]
newfile = sle.join(nla)
if not found:
print('hostmod: host %s not found' %
if newfile == oldfile:
print('hostmod: no changes made', file=sys.stderr)
elif args.update:
with open(args.path, 'w') as f:
if not args.update or args.verbose:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment