How to Update a Hosts File to Block Distractions in Python

This script updates a local hosts file (or a demo file) by adding or updating entries to block distracting websites like Facebook and Twitter.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 11 views 0 copies

Python code

56 lines
Python 3.9+
from pathlib import Path

def update_hosts(entries):
    """
    Add or update blocking entries in the hosts file.
    Uses a local demo file by default to avoid system changes.
    """
    hosts_path = Path("demo_hosts.txt")
    
    # Create demo file if it doesn't exist
    if not hosts_path.exists():
        hosts_path.write_text("127.0.0.1 localhost\n")
    
    # Read current content
    content = hosts_path.read_text()
    lines = content.splitlines()
    
    # Add new blocking entries
    added = []
    updated = []
    for domain in entries:
        entry = f"0.0.0.0 {domain}"
        line_found = False
        
        # Check if domain already exists in hosts file
        for i, line in enumerate(lines):
            if f" {domain}" in line:
                if line.startswith("0.0.0.0"):
                    lines[i] = entry
                    updated.append(domain)
                line_found = True
                break
        
        if not line_found:
            lines.append(entry)
            added.append(domain)
    
    # Write back
    hosts_path.write_text("\n".join(lines) + "\n")
    
    # Report results
    print(f"Added {len(added)} entries: {', '.join(added)}")
    print(f"Updated {len(updated)} entries: {', '.join(updated)}")
    print("\nCurrent hosts file:")
    print(hosts_path.read_text())

if __name__ == "__main__":
    # Block distraction sites
    sites_to_block = [
        "facebook.com",
        "twitter.com",
        "instagram.com",
        "youtube.com"
    ]
    
    update_hosts(sites_to_block)

Output

stdout
Added 4 entries: facebook.com, twitter.com, instagram.com, youtube.com
Updated 0 entries: 

Current hosts file:
127.0.0.1 localhost
0.0.0.0 facebook.com
0.0.0.0 twitter.com
0.0.0.0 instagram.com
0.0.0.0 youtube.com

How it works

The script first checks if a demo hosts file exists; if not, it creates one with a basic localhost entry. It reads the content, splits it into lines, and for each domain in the input list, checks whether an entry containing that domain already exists (using substring match with a leading space). If found and it starts with '0.0.0.0', it updates the line; if not found, it appends a new blocking line. Finally, it writes the modified content back to the file and prints a summary of added and updated entries. Using a demo file avoids modifying the actual system hosts file, making it safe for testing.

Common mistakes

  • Modifying the real /etc/hosts file without backup or admin rights, which can break networking.
  • Using exact string match without a space may accidentally match subdomains or unrelated lines.
  • Forgetting to add a newline at the end of the file, which can cause display issues.

Variations

  1. Use the actual hosts file path (e.g., '/etc/hosts' on Linux/macOS or 'C:\Windows\System32\drivers\etc\hosts' on Windows) for real blocking.
  2. Read entries from a configuration file or command-line arguments instead of a hardcoded list.

Real-world use cases

  • Automating the addition of new blocked domains to a company's hosts-based content filtering system during a cybersecurity response.
  • Setting up a personal productivity script that periodically adds or removes distracting sites' entries based on work hours.
  • Managing a lab's group policy where hosts file changes must be logged and rolled back for testing purposes.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.