Created
April 2, 2020 10:59
-
-
Save alexkiro/a1b3afd23caccc61c51164826adf4183 to your computer and use it in GitHub Desktop.
Ad blocker via /etc/hosts
This file contains hidden or 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 python3 | |
""" | |
Enable or disable ad blocker via /etc/hosts file | |
""" | |
import os | |
import sys | |
import shutil | |
import argparse | |
import requests | |
import subprocess | |
def main(): | |
parser = argparse.ArgumentParser( | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter | |
) | |
parser.add_argument("action", default="enable", choices=["enable", "disable"], nargs="?") | |
args = parser.parse_args() | |
if os.name == "nt": | |
fn = r"c:\windows\system32\drivers\etc\hosts" | |
else: | |
fn = "/etc/hosts" | |
link = "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts" | |
splitter = "#===ad-blocks" | |
ad_hosts = requests.get(link).text | |
etc_hosts = open(fn).read() | |
local_hosts = etc_hosts.split(splitter, 1)[0].strip() | |
if args.action == "disable": | |
open(fn, "w").write("\n\n".join([local_hosts]) + "\n") | |
print("Ad block disabled") | |
else: | |
open(fn, "w").write("\n\n".join([local_hosts, splitter, ad_hosts]) + "\n") | |
print("Ad block enabled/updated") | |
print("Attempting to flush DNS cache") | |
output = "" | |
if shutil.which("systemd-resolve"): | |
output = subprocess.check_output([shutil.which("systemd-resolve"), "--flush-caches"]) | |
else: | |
print("No known method of DNS cache flushing.") | |
if output: | |
print(output) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment