Daily Python
Published in

Daily Python

Python script to block Websites !!! | Daily Python #22

This article is a tutorial on how to block websites in a given time frame.

Requirements:

  1. Python 3.0
  2. Pip

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

Path to the hosts file in Windows

Content of the ‘hosts’ file

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.

Gmail blocked by the Python script

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

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.

Follow the Daily Python Challenge here:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store