# Host File Website Blocker

This utility blocks access to specific websites by modifying the operating system's `hosts` file. It redirects the target domains to `127.0.0.1` (localhost), causing the browser to fail when trying to connect.

**Modules Used:**
*   `os`: To determine the operating system and file paths.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.
*   `ctypes`: (Windows only) To check for administrative privileges.

## The Code

Save this as `blocker.py`.

```python
import os
import sys
import argparse

# Determine hosts file path based on OS
if os.name == 'nt':
    HOSTS_PATH = r"C:\Windows\System32\drivers\etc\hosts"
else:
    HOSTS_PATH = "/etc/hosts"

REDIRECT_IP = "127.0.0.1"

def is_admin():
    """Checks if the script has admin/root privileges."""
    try:
        if os.name == 'nt':
            import ctypes
            return ctypes.windll.shell32.IsUserAnAdmin() != 0
        else:
            return os.getuid() == 0
    except:
        return False

def block_sites(websites):
    if not is_admin():
        print("Error: This script requires Administrator/Root privileges to modify the hosts file.")
        return

    print(f"Blocking: {', '.join(websites)}")
    
    try:
        with open(HOSTS_PATH, 'r+') as file:
            content = file.read()
            for site in websites:
                if site in content:
                    print(f"  Skipping {site} (already blocked)")
                else:
                    # Block domain and www.domain
                    file.write(f"{REDIRECT_IP} {site}\n")
                    file.write(f"{REDIRECT_IP} www.{site}\n")
                    print(f"  Blocked {site}")
    except PermissionError:
        print("Permission denied. Please run as Administrator/Root.")

def unblock_sites(websites):
    if not is_admin():
        print("Error: This script requires Administrator/Root privileges.")
        return

    print(f"Unblocking: {', '.join(websites)}")
    
    try:
        with open(HOSTS_PATH, 'r') as file:
            lines = file.readlines()

        with open(HOSTS_PATH, 'w') as file:
            for line in lines:
                # Check if line contains any of the target websites
                # We split the line to ensure we are matching the domain part
                parts = line.split()
                
                is_target = False
                if len(parts) >= 2 and parts[0] == REDIRECT_IP:
                    domain = parts[1]
                    for site in websites:
                        if domain == site or domain == f"www.{site}":
                            is_target = True
                            print(f"  Unblocked {domain}")
                            break
                
                if not is_target:
                    file.write(line)
    except PermissionError:
        print("Permission denied. Please run as Administrator/Root.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Host File Website Blocker")
    subparsers = parser.add_subparsers(dest="command", help="Command to run")

    # Block Command
    block_parser = subparsers.add_parser("block", help="Block websites")
    block_parser.add_argument("websites", nargs="+", help="List of websites to block")

    # Unblock Command
    unblock_parser = subparsers.add_parser("unblock", help="Unblock websites")
    unblock_parser.add_argument("websites", nargs="+", help="List of websites to unblock")

    args = parser.parse_args()

    if args.command == "block":
        block_sites(args.websites)
    elif args.command == "unblock":
        unblock_sites(args.websites)
    else:
        parser.print_help()
```

## Usage

**Windows:** Open Command Prompt as Administrator.
**Linux/macOS:** Use `sudo`.

```bash
# Block Facebook and YouTube
python blocker.py block facebook.com youtube.com

# Unblock them
python blocker.py unblock facebook.com youtube.com
```

[[programming/python/python]]