Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chặn trang web với Python (Website Blocker)

Thay vì dùng phần mềm thứ 3, tự viết script Python chặn trang web (Facebook, YouTube...) trong khung giờ làm việc (9h-18h) bằng cách sửa file hosts của hệ điều hành.

Nguyên lý

File hosts ánh xạ hostname → IP. Thêm dòng 127.0.0.1 domain.com sẽ chuyển hướng domain về localhost (chặn truy cập).

Vị trí file hosts

  • Windows: C:\Windows\System32\drivers\etc\hosts
  • Linux/macOS: /etc/hosts

Cần quyền Administrator/root để ghi file.

Mã nguồn Website Blocker

import time
from datetime import datetime as dt

# Đường dẫn file hosts (Windows)
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"

# Danh sách trang web cần chặn
websites = [
    "www.youtube.com", "youtube.com",
    "www.facebook.com", "facebook.com",
    "www.instagram.com", "instagram.com"
]

while True:
    now = dt.now()
    work_start = dt(now.year, now.month, now.day, 9)
    work_end = dt(now.year, now.month, now.day, 18)
    
    if work_start < now < work_end:
        print("Đang chặn trang web... (9h-18h)")
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for site in websites:
                if site not in content:
                    file.write(redirect + " " + site + "\n")
    else:
        print("Cho phép truy cập (ngoài giờ làm việc)")
        with open(hosts_path, 'r+') as file:
            lines = file.readlines()
            file.seek(0)
            for line in lines:
                if not any(site in line for site in websites):
                    file.write(line)
            file.truncate()
    
    time.sleep(5)  # Kiểm tra mỗi 5 giây

Kết quả

Trong giờ làm việc (9h-18h): Truy cập YouTube/Facebook báo lỗi "Cannot connect" hoặc "Site blocked".

Ngoài giờ: Truy cập bình thường.

Tuỳ chỉnh

  • Thay đổi work_start, work_end
  • Thêm/bớt domain trong list websites
  • Thêm thông báo tùy chỉnh
  • Chạy nền dưới dạng service/daemon

Lưu ý

  • Cần chạy với quyền Admin (Windows) hoặc sudo (Linux/macOS)
  • Một số trình duyệt cache DNS → cần clear cache hoặc khởi động lại browser
  • HTTPS vẫn bị chặn vì DNS resolve về 127.0.0.1 trước khi TLS handshake