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.
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.
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 “youtube.com”, 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 −
#Import libraries import time from datetime import datetime as dt #Windows host file path hostsPath=r"C:\Windows\System32\drivers\etc\hosts" redirect="127.0.0.1" #Add the website you want to block, in this list websites=["www.youtube.com","youtube.com", "www.facebook.com", "facebook.com"] while True: #Duration during which, website blocker will work if dt(dt.now().year,dt.now().month,dt.now().day,9) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,18): print ("Sorry Not Allowed...") with open(hostsPath,'r+') as file: content = file.read() for site in websites: if site in content: pass else: file.write(redirect+" "+site+"\n") else: with open(hostsPath,'r+') as file: content = file.readlines() file.seek(0) for line in content: if not any(site in line for site in websites): file.write(line) file.truncate() print ("Allowed access!") time.sleep(5)
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 – youtube.com or facebook.com, we’ll get −
We can customize above code as per our requirement like duration, websites, custom messages etc.