DEV Community

Cover image for How to build website blocker in Python
Jordan Kalebu
Jordan Kalebu

Posted on • Updated on

How to build website blocker in Python

Hi guys

Many of us struggle to focus nowadays, easily distracted by Social media and some sites on the internet which dramatically affecting our productivity.

In this tutorial, you will learn and build your own website blocker to block certain selected sites that distract you during working hours.

Requirements

We are going to use the time and Datetime Module only which comes by default with the Python Standard Library therefore you don’t need to install anything.

How do we block sites?

Every operating system has a host file and it’s on this file where we are going to add a list of websites we want to block by redirecting them to 127.0.0.1 (localhost).

We will add website URLs to the host file and mapping them to the localhost thus preventing you from accessing the real site during working hours.

Instead of adding www.facebook.com we are going to add 127.0.0.1 www.facebook.com, therefore whenever a user tries to access the website during working hours will be directed to the localhost.

Therefore we need to add those sites to the host files during working hours and removing them immediately when it’s going home time.

if working_time:
  add mapped websites url to host file 
else:
  remove the website files from the host file 
Enter fullscreen mode Exit fullscreen mode

Location of host file

Host file that we need to edit is stored on different path depending on the Operating system you’re using

For those in Linux

Linux_host = "/etc/hosts"
Enter fullscreen mode Exit fullscreen mode

For those in window

Window_host = r"C:\Windows\System32\drivers\etc\hosts"
Enter fullscreen mode Exit fullscreen mode

Building our Website Blocker

Importing modules & pre-configuring

import time
from datetime import datetime as dt

sites_to_block = [
    'www.facebook.com',  'facebook.com',  
    'www.youtube.com', 'youtube.com',
    'www.gmail.com', 'gmail.com'
]

Linux_host = '/etc/hosts'
Window_host = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
Enter fullscreen mode Exit fullscreen mode

We then required to add the sites to be blocked during working hours and remove them when it is not, I have made a simple function just to do that as shown in the source code below

Note
If your own Window change the default_hoster to Window_host

import time
from datetime import datetime as dt

sites_to_block = [
    'www.facebook.com',  'facebook.com',  
    'www.youtube.com', 'youtube.com',
    'www.gmail.com', 'gmail.com'
]

Linux_host = '/etc/hosts'
MacOs_host = '/private/etc/hosts'
Window_host = r"C:\Windows\System32\drivers\etc\hosts"
default_hoster = Linux_host
redirect = "127.0.0.1"

def block_websites(start_hour , end_hour):
    while True:
        if dt(dt.now().year, dt.now().month, dt.now().day,start_hour)< dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,end_hour): 
            print("Do the work ....")
            with open(default_hoster, 'r+') as hostfile:
                hosts = hostfile.read()
                for site in  sites_to_block:
                    if site not in hosts:
                       hostfile.write(redirect+' '+site+'\n')
        else:
            with open(default_hoster, 'r+') as hostfile:
                hosts = hostfile.readlines()
                hostfile.seek(0)
                for host in hosts:
                    if not any(site in host for site in sites_to_block):
                        hostfile.write(host)
                hostfile.truncate()
            print('Good Time')
        time.sleep(3)

if __name__ == '__main__':
    block_websites(9, 18)
Enter fullscreen mode Exit fullscreen mode

The function receives two-parameter, One is the starting time on which for testing I set as 9 am and the ending time for a job which I initially set 18 but you can twist it whatever you want.

When you run the above code, It will do as we have said, you can try accessing sites you listed in sites_to_block it will redirect you to the localhost.

If you find it interesting, Don't be shy share it with your fellow tech nerds so as more can learn this trick

The Original Article can be found on kalebujordan.dev

GitHub logo Kalebu / Website-blocker-python

A simple website blocker project implemented in Python, It can be used to block certain websites during working time to reduce distraction thus improving productivity

Website Blocker Python

Intro

Hi Guys 👋

This repository consists the code of a simple website blocker project implemented in Python. It can be used to block certain websites during work time to reduce distraction thus improving productivity.

The magic

The magic of this project lies on modifying the host file within your computer that manages how you access the web.

Getting started

Well to get started with this project just clone the repository and edit the host file location depending on the OS your using.

    $-> git clone https://github.com/Kalebu/Website-blocker-python
    $-> cd Website-blocker-python
    $ Website-blocker-python ->
Enter fullscreen mode Exit fullscreen mode

Adding sites to block + Editing host files

Now open the app.py and then go to line 4 with variable site_to_block and you can add the sites you would like to block during work time

the script will automaticaly detect your OS and will add the host records to the relevent…

Top comments (19)

Collapse
 
vampiire profile image
Vamp • Edited

neat article thanks for sharing. an alternative approach is to create a hosts.blocked file. then use a cron job (or python) to simply swap the files:

create two files:
hosts.original (copy of original etc hosts)
hosts.blocked (original + deadend for blocked sites)

(on)
copy hosts.blocked to etc hosts

(off)
copy hosts.original to etc hosts

this will ensure you are not mutating the original file. you can then convert your tool to generate the .blocked file based on that list of sites (auto appending common prefixes like www)

Collapse
 
mehemmedmehdipy profile image
MehemmedMehdiPY

Hello. I registered on the website newly in order to get some help about this blog. Firstly, this article is so understandable including code part. However, questions are inevitable. I spent several hours to understand the project, but couldn't get why we should use truncate(), seek(), and write() (to rewrite) in "else" part. I searched how the first two functions work, and tried trial and error tactics to understand the functionality of code. In conclusion, only "else" part of python code is not comprehensive to me. I would be glad if I get help. Thanks in advance

Collapse
 
d1p profile image
Debashis Dip

Or, remove the date time check from python code and run the script as a cronjob and then you don’t need to run the script and open the file over and over.

Collapse
 
theviklink profile image
TheVikLink

From where do I run this program?

Collapse
 
kalebu profile image
Jordan Kalebu

For testing just run it as a program ... but for it to keep running for quite a while in your background, It's advised to run it as a process

Collapse
 
swayamkulkarni18 profile image
Swayam Kulkarni

Hi!!👌🖐️ thanks bro!

Collapse
 
kalebu profile image
Jordan Kalebu

You're welcome @Swayam-KULKARNI

Collapse
 
vedantmadane profile image
Vedant Madane

PermissionError: [Errno 13] Permission denied: 'C:\Windows\System32\drivers\etc\hosts'

Collapse
 
kalebu profile image
Jordan Kalebu

You need to run the python script with administrator privileges, Try checking out on this StackOverflow comment they explained how to deal with it

stackoverflow.com/questions/130763...

Collapse
 
emanuel937 profile image
Emanuel937

you will need root permission to run this code

Collapse
 
emanuel937 profile image
Emanuel937

this article is copy and paste ......

Collapse
 
alvinjfguo profile image
alvinjfguo

i can run the program, it prompted a cmd window thing with the "do the work" text, but i can still open facebook. how to fix this?

Collapse
 
kalebu profile image
Jordan Kalebu

Sometimes the issue can be you're accessing a subdomain that is not listed on the sites to be blocked, can you access all the sites in sites to be blocked list or is it just Facebook?

Collapse
 
punkindapie profile image
ThiccPie

I know am kinda late but do I need to create a folder for this script if I want it to run cause for the add mapped website url to host file part it comes up with a syntax error any help?

Collapse
 
kalebu profile image
Jordan Kalebu

Can you share your codebase?