How to Block Websites with Python

First, let’s find the hosts file stored by the operating system

This is image title

Path to the hosts file in Windows

Content of the ‘hosts’ file

This is image title

Snip of the contents of the hosts file

What is the ‘hosts’ file?

The host is an operating system file that maps hostnames to IP addresses. In this program, we will be mapping hostnames of websites to our localhost address. Using python file handling manipulation we will write the hostname in hosts.txt and remove the lines after your working hours.

Note: The location of the host file may be different for different operating systems. Windows Users should create a copy of this hosts file.

Let’s write the Python script that will do the task

# Run this script as Administrator
import time 
from datetime import datetime as dt

hostsFilePath = "C:\\Windows\\System32\\drivers\\etc\\hosts"
# localhost's IP Address 
redirect_IP = "127.0.0.1"

# Websites that you want to block 
website_list =["www.facebook.com","facebook.com", 
  "www.gmail.com","gmail.com"]
while True: 
 # time of your work 
 if dt(dt.now().year, dt.now().month, dt.now().day,8) \
 < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,21): 
  with open(hostsFilePath, 'r+') as file: 
   content = file.read() 
   for website in website_list: 
    if website in content: 
     pass
    else: 
     # Mapping hostnames to be blocked to your localhost IP address 
     file.write(redirect_IP + " " + website + "\n") 
     print("Access Denied...") 
 else: 
  with open(hostsFilePath, 'r+') as file: 
   content=file.readlines() 
   file.seek(0) 
   for line in content: 
    if not any(website in line for website in website_list): 
     file.write(line) 
   # Removing hostnmes from hosts file 
   file.truncate() 
  print("Access Granted...") 
 time.sleep(5)

Change the extension of the Python file from ‘.py’ to ‘.pyw’ and run the script as Administrator to gain access to the hosts file.

This is image title

Gmail blocked by the Python script

You can also, schedule the above script to run At startup

This is image title

This is image title

This is image title

This is image title

This is image title

This is image title

This is image title

Finally, Restart your machine, and check if the website blocker works.

I hope this article was helpful, do leave some claps if you liked it.

Thank you for reading!

#python #programming #tutorial

How to Block Websites with Python
21.45 GEEK