Adblocker Script (Python)

Download Python Script


import os
import platform
import subprocess
import requests

# Copyright (c) Steven Black

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights# 
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# May need to adjust define OS-specific hosts file path
if platform.system() == "Windows":
    hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
else:
    hosts_path = "/etc/hosts"

redirect_ip = "0.0.0.0"

# URL to Steven Black's Unified Hosts list (blocks ads, malware, etc.)
BLOCKLIST_URL = "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"

def get_remote_blocklist():
    """Download the updated blocklist from GitHub."""
    print(f"Downloading blocklist from {BLOCKLIST_URL}...")
    try:
        response = requests.get(BLOCKLIST_URL)
        response.raise_for_status() # Check for bad responses
        
        domains = set()
        for line in response.text.splitlines():
            line = line.strip()
            # We want lines that start with 0.0.0.0 (or 127.0.0.1) and a domain name
            if line and (line.startswith("0.0.0.0") or line.startswith("127.0.0.1")):
                parts = line.split()
                if len(parts) >= 2:
                    domains.add(parts[1]) # Add only the domain name
        
        print(f"Successfully downloaded {len(domains)} domains.")
        return domains
    except requests.exceptions.RequestException as e:
        print(f"Error downloading blocklist: {e}")
        return set()

def modify_hosts(domains_to_block):
    try:
        with open(hosts_path, 'r') as file:
            lines = file.readlines()
        
        # Keep original localhost entries, remove old ad entries
        clean_lines = [line for line in lines if not line.strip().startswith(redirect_ip) and not line.strip().endswith("localhost")]

        with open(hosts_path, 'w') as file: # Changed to 'w' (write) mode to overwrite clean content
            file.writelines(clean_lines) # Write back original clean entries
            # Add all new domains
            for domain in domains_to_block:
                file.write(f"\n{redirect_ip} {domain}")
            print(f"Successfully wrote {len(domains_to_block)} new entries to hosts file.")

        # Flush DNS 
        print("Flushing DNS cache...")
        if platform.system() == "Windows":
            subprocess.run(["ipconfig", "/flushdns"], capture_output=True)
            
        print("Success! Ad blocker is now powerful and active.")

    except PermissionError:
        print("ERROR: You must run this script with Administrator/Root privileges.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    remote_domains = get_remote_blocklist()
    if remote_domains:
        modify_hosts(remote_domains)