TECH PIXEL

"Tech Pixel": Clearly mentions the site name. "Your go-to source for the latest tech news, reviews, and tutorials": Summarizes what the site offers. "Stay updated with the newest trends in technology": Highlights the value of staying current with tech trends. "Enhance your skills with our expert guides": Emphasizes the practical benefits and expertise available on the site.

How to Build A Website Blocker With Python | Website Blocker Python Project


import datetime

import time

end_time= datetime.datetime(2024,9,4)
site_block= ["www.techpixel.xyz", "www.facebook.com"]
host_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"

while True:
if datetime.datetime.now()<end_time:
print("start blocking")
with open(host_path, "r+") as host_file:
content= host_file.read()
for website in site_block:
if website not in content :
host_file.write(redirect + " " + website + "\n")

else:
pass


else:
with open(host_path, "r+") as host_file:
content = host_file.readlines()
host_file.seek(0)
for lines in content:
if not any(website in lines for website in site_block):
host_file.write(lines)

host_file.truncate()
time.sleep(5)

  • Setup: The script begins by importing the necessary modules and setting up the parameters. It defines the end time for blocking websites, the list of sites to block, the path to the hosts file, and the IP address to redirect blocked sites to (which is usually 127.0.0.1, or localhost).

  • Infinite Loop: The script enters an infinite loop to continuously check if the current date and time are before the specified end time.

  • Blocking Websites: While the current time is before the end time, the script prints a message indicating that blocking has started. It then opens the hosts file and reads its contents. For each website in the list of sites to block, it checks if the website is already in the hosts file. If it isn’t, the script adds an entry to redirect the website to 127.0.0.1, effectively blocking it.

  • Unblocking Websites: Once the current time passes the end time, the script stops blocking websites and starts the process of unblocking them. It reads the contents of the hosts file and then opens it for writing. It writes back only those lines that do not contain the blocking entries for the websites. This removes the blocking entries for the sites that were previously blocked.

  • Sleep Interval: The script waits for 5 seconds before repeating the process. This interval helps to reduce the script’s workload and avoid constant file access.



  • Post a Comment

    0 Comments