Website Blocker Using Python

If you are working in a big IT company then you may notice that their couple of websites are blocked especially social networking sites like facebook, youtube, Instagram etc.

Instead of using third-party applications to blocks certain website, we can develop our own custom application which will block websites of our choice and developing a website blocker in python is not so difficult too. That’s what we going to do- develop a python script which will block the website we want.


  • Python 3.x installed
  • Basic knowledge of Python

What we are going to do:

We are going to develop python application which will block a certain website (whatever website you want- facebook, youtube etc.) during certain hours of the day(9:00 to 18:00 hours), consider office hours of the day, we want to blocks all social networking sites. We are going to use the python built-in libraries, so no need to install any third party packages.

How do we do it?

Every operating system has a hosts file. Location of the host file may be different for the different operating system. This host file is map hostname to IP address of the machine. In this host file, we going to list websites which we want to block.

Our host file will look something like,

As I have not mentioned, any website name in my host file. If I try to open “”, I can do it without any problem. Below is the screenshot (just to make sure after running my scripts, this website shouldn’t open if I want to block it.)

Below is our website blocker program −

 Live Demo

#Import libraries
import time
from datetime import datetime as dt
#Windows host file path
#Add the website you want to block, in this list
websites=["","", "", ""]
while True:
   #Duration during which, website blocker will work
   if dt(,,,9) < < dt(,,,18):
   print ("Sorry Not Allowed...")
   with open(hostsPath,'r+') as file:
      content =
      for site in websites:
         if site in content:
            file.write(redirect+" "+site+"\n")
      with open(hostsPath,'r+') as file:
      content = file.readlines()
      for line in content:
         if not any(site in line for site in websites):
   print ("Allowed access!")


Sorry Not Allowed...
Sorry Not Allowed...
Sorry Not Allowed...
Sorry Not Allowed...
Sorry Not Allowed...
Sorry Not Allowed...
Sorry Not Allowed...

Now if I try to open – or, we’ll get −

We can customize above code as per our requirement like duration, websites, custom messages etc.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started