Create a Time Wasting Websites Blocker using Python

a time wasting website blocker using python. It will prevent access of some mind destructive websites.

Introduction

In this digital era, most of the facilities have became online. Especially, after the pandemic(Covid) situation people have habituated with the internet. From study to work, internet become the most convenient way to stay connected with each other.

Since study became online too, parents are concerned to keep their child from visiting any mind destructive websites or content. Not only study, a harmful content or site can de-focused a mature person too from a productive work.

In this tutorial, we will create our own Website Blocker using Python to make this real-life problem grounded. It will block some mind destructive websites(users can set the list as per their requirements) permanently or temporarily(for a time duration: users can set the time as their choice).

☛Learn AlsoHow to Send Emails using Python Program (Complete Tutorial)

How does this Website Blocker work?

Every operating system has a host file called 'hosts' locates in a fixed path depending on the operating system. It's a simple text file, maps hostnames to IP addresses. 

It contains the names of several hosts, including their respective IP addresses. We just need to modify this 'hosts' file by adding the hostnames(website addresses, you want to block) to it.

The location of the host file depends on your OS

The host file is a system file. You'll not be able to modify this file as a normal user. Depending on your Operating System find out the solution given below.

Windows

➜File Location: "C:\Windows\System32\drivers\etc\hosts"

Watch the entire video given below to change the permission of the host file in Windows.

Linux

➜File Location: "/etc/hosts"

In Linux, check the permission of this file first. If the permission is like this: "-rw-r--r--", you need to change it by giving the writing permission to the group.

➜Change the Permission: sudo chmod 777 /etc/hosts

You can re-change the permission of the 'hosts' file again to where it was.

➜Return to the Previous State: sudo chmod 644 /etc/hosts

Mac

For Mac, the process is the same as Linux.

➜Location: "/etc/hosts"

➜Change the Permission: sudo chmod 777 /etc/hosts

Once the host file permissions have changed, you can start writing the code.

Block Websites Permanently

Here, we'll create a python program for blocking the access of some websites permanently. I added a single comment line before each line of the code. It will help you to grab the logic better.

Code


'''A Python Program for Permanent Website Blocker: permanent_blocker.py'''
import platform

my_pc = platform.uname()
# Get your OS name
OS = my_pc.system
# The locations of the 'hosts' file according to the OS.
hosts_path = {
'Linux': "/etc/hosts",
'Windows': "C:\Windows\System32\drivers\etc\hosts",
'Mac': "/private/etc/hosts"
}

# IP address of the localhost.
redirect = "127.0.0.1"
# Websites list those you want to block.
website_list = ['www.facebook.com', 'www.twitter.com', 'www.instagram.com']

# Open the 'hosts' file in the read mode.
with open(hosts_path[OS], 'r') as file:
# Read the content of the 'hosts' file.
content = file.read()
for website in website_list:
# Check if the website is already in the
# 'hosts' file or not
if website in content:
file.truncate()
else:
# If the site isn't present there, add it to there
# Open the 'hosts' file again in read and append mode.
with open(hosts_path[OS], 'a+') as file:
file.write("\n"+redirect+" "+website+"\n")

Block Websites for a routine time

Only use this code to block access to websites for a certain time duration. I've set the duration 10 AM to 10 PM in this program. You can set the time as you need

First, run this program normally for testing purposes and check whether it's working or not.

If it passed the previous step, then, you can set the program as a background process so that it runs automatically without interrupting other tasks. But how to do, right? Go to the next section where I described it for different OS.

Code


'''time_period_blocker.py'''
import time
from datetime import datetime
import platform

my_pc = platform.uname()
# Get your OS name
OS = my_pc.system
# The locations of the 'hosts' file according to the OS.
hosts_path = {
'Linux': "/etc/hosts",
'Windows': "C:\Windows\System32\drivers\etc\hosts",
'Mac': "/private/etc/hosts"
}

# IP address of the localhost.
redirect = "127.0.0.1"
# Websites list those you want to block. You can Modify it.
website_list = ['www.facebook.com', 'www.twitter.com', 'www.instagram.com']

curr = datetime.now()

while True:
if datetime(curr.year, curr.month, curr.day, 10) < \
curr.now() < datetime(curr.year, curr.month, curr.day, 22):
# Open the 'hosts' file in the read mode.
with open(hosts_path[OS], 'r') as file:
# Read the content of the 'hosts' file.
content = file.read()
for site in website_list:
# Check if the website is already in the
# 'hosts' file or not
if site in content:
pass
else:
# If the site isn't present there, add it to there
# Open the 'hosts' file again in read and append mode.
with open(hosts_path[OS], 'a+') as file:
file.write(redirect+" "+site+"\n")
else:
# Open the 'hosts' file in read and write mode.
with open(hosts_path[OS], 'r+') as file:
content = file.readlines()
file.seek(0)
for line in content:
if not any(site in line for site in website_list):
file.write(line)
file.truncate()
time.sleep(5)

Explanation of the above Code

As you can see, we imported three modules here, time, datetime, and platform.

my_pc.system: Returns the OS name of the system, and based on this result we'll find the path of the 'hosts' file of the respective Operating System.

hosts_path: It's a python dictionary containing the path of the 'hosts' file according to the OS.

website_list: It's a python list containing three websites name I want to block from accessing. You can modify(add more or remove) it as per your requirement.

date_time.now(): Returns the current date and time, stores into a variable called 'curr'.

Next, we declared a while loop for running infinitely.

The if statement checks if the current time is between the time we've set for preventing the access of those websites or not.

with open(hosts_path[OS], 'r') as file: Opens the 'hosts' file in read mode.

file.read(): Read the content of the 'hosts' file and stores into 'content' variable.

if site in content: Checks if any website from 'website_list' is already presented in the 'hosts' file or not. If the return value is False then the program follows the next step.

with open(hosts_path[OS], 'a+') as file: Opens the 'hosts' file again in read and append mode, for appending the websites those are not present in the file but presented in this python list, 'websites_list'.

Remember, our code has been set for running infinite time. So, when it will found the current time is not between 10 AM and 10 PM, the code will remove those hostnames(or websites) added to the 'hosts' file; so that you can access those again.

Run this Program as a Background Process

You can set the previous Website Blocker Program(for a routine time) as a background process so that you can do other tasks simultaneously without disturbing it from the running state. Find out the way according to your Operating System.

Windows

Use 'pythonw' instead of 'python' while running the program. The program will start running as a background process automatically.

☛Command: pythonw time_period_blocker.py

Linux

nohup indicates No Hangup. It implies don't terminate any process if the parent process has been killed, and it will create a nohup.out file in the same directory where the program file is in.

Am Percent(&) indicates to run the program in the background.

☛Command: nohup python3 time_period_blocker.py &

Mac

Same as Linux.

☛Command: nohup python3 time_period_blocker.py &

Make the Program a Startup Process

If you want your website blocker program starts running automatically when your system turns on, then you need to set the python program as a startup process. But how to do, right? Watch the entire video given below. 

The video will show you the output of the above program as well as the steps you need to follow for making it a startup process.

If you want to get only the desired result of the previous task, simply start watching from 3:00.

The Output

☛Visit AlsoSend Secret Messages to Your Friends using Python

Summary

In this tutorial, we build a website blocker using python. We made two programs here. One is for blocking access to some websites permanently and another one is for a time duration only(Working or Study time).

You just need to follow the steps one after one, described above. Despite that if you get any trouble to run this project, let me know in the comment section, I will guide you.

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post