Last active
July 9, 2020 03:37
-
-
Save Rainyan/9466090639c91e38102a57ac1167d62f to your computer and use it in GitHub Desktop.
Check hosts file for dodgy entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse, os, platform, sys | |
def is_safe(line): | |
if (is_empty_line(line) or | |
is_comment(line) or | |
is_safe_redir(line)): | |
return True | |
return False | |
def is_empty_line(line): | |
return len(line.strip()) == 0 | |
def is_comment(line): | |
return line.strip()[:1] == '#' | |
def is_safe_redir(line): | |
safe_addrs = [ | |
'0.0.0.0', | |
'127.0.0.1', | |
'127.0.1.1', | |
'127.0.0.53', | |
'255.255.255.255', | |
'::1', | |
'fe80::1%lo0', | |
'ff00::0', | |
'ff02::1', | |
'ff02::2', | |
'ff02::3', | |
] | |
for addr in safe_addrs: | |
addr_w_space = addr + ' ' | |
if (len(line) >= len(addr_w_space) and | |
line[:len(addr_w_space)] == addr_w_space): | |
return True | |
# Continue looping if not at last iteration | |
elif not addr == safe_addrs[-1]: | |
continue | |
return False | |
def print_nonewline(line): | |
sys.stdout.write(line) | |
def check_hosts(hosts_path): | |
unsafe_lines = [] | |
with open(hosts_path, 'r') as f: | |
for line in f: | |
if not is_safe(line): | |
unsafe_lines.append(line) | |
num_results = len(unsafe_lines) | |
print('Found ' + str(num_results) + ' lines to manually check.') | |
linenum = 0 | |
for line in unsafe_lines: | |
fline = '- line ' + str(linenum) + ':\t' + line | |
print_nonewline(fline) | |
linenum += 1 | |
print('') | |
def get_system_default_hosts_path(): | |
if platform.system().lower().startswith('win'): | |
return os.fsdecode(os.path.join(os.environ['SystemRoot'], | |
'System32' + os.sep + 'drivers' + os.sep + 'etc' + os.sep + 'hosts')) | |
else: | |
return '/etc/hosts' | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
help_str = 'hosts file location to perform checks on; if undefined, will use ' +\ | |
get_system_default_hosts_path() | |
parser.add_argument('-f', '--file', help=help_str) | |
args = parser.parse_args() | |
if args.file: | |
check_hosts(args.file) | |
else: | |
check_hosts(get_system_default_hosts_path()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment