Website Blocker Using Python

Website blockers are commonly used in corporate environments to restrict access to social media and entertainment sites during work hours. Instead of relying on third-party applications, we can create our own custom website blocker using Python's built-in libraries.

Prerequisites

  • Python 3.x installed
  • Basic knowledge of Python
  • Administrator privileges (required to modify system files)

How It Works

Every operating system has a hosts file that maps hostnames to IP addresses. By redirecting blocked websites to the local loopback address (127.0.0.1), we can prevent access to specific sites during designated hours.

User Request Hosts File 127.0.0.1 youtube.com Blocked Site Unreachable Python Script Controls Timing Blocks during work hours (9 AM - 6 PM)

Website Blocker Implementation

Here's the complete Python script that blocks specified websites during work hours ?

import time
from datetime import datetime as dt

# Windows hosts file path (modify for other OS)
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"

# Websites to block
blocked_sites = ["www.youtube.com", "youtube.com", "www.facebook.com", "facebook.com"]

print("Website blocker started...")

while True:
    # Check if current time is during work hours (9 AM to 6 PM)
    if dt(dt.now().year, dt.now().month, dt.now().day, 9) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 18):
        print("Work hours - blocking websites...")
        
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for site in blocked_sites:
                if site not in content:
                    file.write(redirect + " " + site + "\n")
    else:
        print("Non-work hours - allowing access...")
        
        with open(hosts_path, 'r+') as file:
            content = file.readlines()
            file.seek(0)
            
            for line in content:
                if not any(site in line for site in blocked_sites):
                    file.write(line)
            
            file.truncate()
    
    time.sleep(5)

Cross-Platform Compatibility

The hosts file location varies by operating system ?

import platform
import os

def get_hosts_path():
    system = platform.system()
    
    if system == "Windows":
        return r"C:\Windows\System32\drivers\etc\hosts"
    elif system in ["Linux", "Darwin"]:  # Darwin is macOS
        return "/etc/hosts"
    else:
        raise OSError(f"Unsupported operating system: {system}")

# Usage
hosts_path = get_hosts_path()
print(f"Hosts file location: {hosts_path}")

Enhanced Version with Configuration

A more flexible implementation with customizable settings ?

import time
import json
from datetime import datetime as dt

class WebsiteBlocker:
    def __init__(self, config_file="blocker_config.json"):
        self.config = self.load_config(config_file)
        self.hosts_path = self.config["hosts_path"]
        self.redirect = "127.0.0.1"
    
    def load_config(self, config_file):
        default_config = {
            "hosts_path": r"C:\Windows\System32\drivers\etc\hosts",
            "blocked_sites": ["youtube.com", "facebook.com"],
            "start_hour": 9,
            "end_hour": 18
        }
        
        try:
            with open(config_file, 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            return default_config
    
    def is_work_hours(self):
        now = dt.now()
        start = dt(now.year, now.month, now.day, self.config["start_hour"])
        end = dt(now.year, now.month, now.day, self.config["end_hour"])
        return start < now < end
    
    def block_sites(self):
        try:
            with open(self.hosts_path, 'r+') as file:
                content = file.read()
                for site in self.config["blocked_sites"]:
                    if site not in content:
                        file.write(f"{self.redirect} {site}\n")
            print("Sites blocked successfully")
        except PermissionError:
            print("Error: Run as administrator to modify hosts file")
    
    def unblock_sites(self):
        try:
            with open(self.hosts_path, 'r+') as file:
                lines = file.readlines()
                file.seek(0)
                
                for line in lines:
                    if not any(site in line for site in self.config["blocked_sites"]):
                        file.write(line)
                
                file.truncate()
            print("Sites unblocked successfully")
        except PermissionError:
            print("Error: Run as administrator to modify hosts file")

# Example usage
if __name__ == "__main__":
    blocker = WebsiteBlocker()
    
    while True:
        if blocker.is_work_hours():
            blocker.block_sites()
        else:
            blocker.unblock_sites()
        
        time.sleep(60)  # Check every minute

Important Notes

  • Administrator Privileges: The script requires admin rights to modify the hosts file
  • Browser Cache: Clear browser cache or restart browser for changes to take effect
  • Security: Be cautious when modifying system files
  • Testing: Test with a single website before blocking multiple sites

Conclusion

This Python website blocker provides a simple yet effective way to restrict access to specific websites during designated hours. The enhanced version with configuration files offers flexibility for different use cases and environments.

Updated on: 2026-03-25T05:23:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements