🚫 Adblocker Script (Python)

⚠️ ADMIN PRIVILEGES REQUIRED: This script must be run with administrator/root privileges to modify the system hosts file.

📋 Script Information

Language
Python 3
Source
Steven Black's Unified Hosts
License
MIT
Platforms
Windows, Linux, macOS

📌 Description

This Python script downloads Steven Black's unified hosts file from GitHub and updates the system hosts file to block ads, malware, and tracking domains network-wide. It works on Windows, Linux, and macOS by automatically detecting the correct hosts file location.

🔧 Features

📥 Download

⬇️ Download adblocker.py

Right-click and "Save Link As..." if download doesn't start

📝 Usage

# Run with administrator/root privileges

# Windows (Command Prompt as Admin):
python adblocker.py

# Linux/macOS:
sudo python3 adblocker.py

📋 Requirements

🔍 How It Works

  1. Downloads the latest unified hosts file from GitHub
  2. Parses domain entries from lines starting with 0.0.0.0 or 127.0.0.1
  3. Reads current hosts file and removes old ad blocking entries
  4. Writes new domains to hosts file (redirected to 0.0.0.0)
  5. Flushes DNS cache on Windows for immediate effect

📄 Full 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.

# 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
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()
        
        domains = set()
        for line in response.text.splitlines():
            line = line.strip()
            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])
        
        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:
            file.writelines(clean_lines)
            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 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)

📜 License

This script is Copyright (c) Steven Black and released under the MIT License. See the script header for full license text.

🔗 Source

Original blocklist source: StevenBlack/hosts on GitHub

← Back to Scripts