Website Blocker Using Python

Website Blocker Using Python

This blog will discuss the development of a Website Blocker using Python. This blog will teach you about the following things.

  • List Operations
  • File Handling
  • Permission Handling
  • String Operation
  • Specifying the return type of a function

Operations on a file by programming an application is file handling. In Python, we can open a file using the open() function built into Python.

Let’s discuss the main idea first. There is a file named “hosts” in Windows at generally at System32/drivers. This file will help us block a website from being accessed from the computer. We need to add 127.0.0.1 website.com at the end of the file to block the website. And similarly, remove it to unblock the website.

However, since this is an important system file, you cannot edit it in a simple way. You will need administrative privileges to edit it. So, to overcome this problem, you have two solutions. Either run the Python IDLE as an administrator and run the Python file. Or, you can run the Command Prompt as an administrator and run the python file using the command: “python filename.py“.

Website Blocker function in Python

def blocker():
    ip = "127.0.0.1"
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as host:
        content = host.read()
        for i in all_websites():
            if i in content:
                print(i + " is already blocked")
                pass
            else:
                what_to_write = ip + "       " + i + "\n"
                host.write(what_to_write)

First, we will open the hosts’ file to read and write content in it. We will loop through the list of websites to block and check if each one of them exists in the file. If it does, then we will display that it is already blocked, and if not, we will add the website to the file in the syntax: “127.0.0.1 website.com“. The “\n” represents that the next string will start in the next line. We will then write on that file using the syntax: “fileName.write(string)“.

  • open() – This function will help us work with a particular file, read, write, or both.
  • pass – This is a keyword in Python used when there is no code to write for now, but the error will also be avoided. For example, if you don’t know what to write in the else section of the conditional and you want to write it later, then you can leave it by writing pass, which will not throw any error.
  • .read() – This method is used to read the content of the file.
  • .write() – This method is used to append the string to the EOF.

all_websites() function

def all_websites() -> list:
    a = int(input("how many websites? "))
    website_list = []
    for i in range(a):
        website_list.append(str(input("Enter the website URL: ")))

    return website_list

Here, we will ask how many websites to store, then loop that many times. Each time we will ask for a new website and append it to a website_list list which was defined previously. At last, we will return it. You may be wondering what the “-> list” means in the first line. This represents that the return type of that particular function will be a list. In our case, the return type of the website_list variable is also a list. Did you know we can check the type of a variable using the syntax: “print(type(variable_name))”

Website unblocker function in Python

def unblocker():
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as host:
        content = host.read()
        my_websites = all_websites()
        for i in range(len(my_websites)):
            if my_websites[i] in content:
                new_content = content.replace(my_websites[i], "")
                host.truncate(0)
                host.write(new_content)
            else:
                print(i + " has not been blocked")

Here, we will open the host file and store the websites we want to unblock in my_websites by calling the all_websites() function. Then, we will loop through all the desired websites one by one and check if they exist in the host file and if so, we will replace the website domain with a null string of “” in a variable new_content. Then, since the write method will only append the desired content to the file, we will first need to erase the current data of the file. We can do this using the truncate method.

After we remove the initial data of the host file, we will append our new_content to the host file using the write() method. If the desired website has not been blocked or doesn’t exist in the host file, then the program will warn them about it.

Complete code to create a Website Blocker Using Python:

def all_websites() -> list:
    a = int(input("how many websites? "))
    website_list = []
    for i in range(a):
        website_list.append(str(input("Enter the website URL: ")))

    return website_list

def blocker():
    ip = "127.0.0.1"
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as host:
        content = host.read()
        for i in all_websites():
            if i in content:
                print(i + " is already blocked")
                pass
            else:
                what_to_write = "\n" + ip + "       " + i + "\n"
                host.write(what_to_write)

def unblocker():
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as host:
        content = host.read()
        my_websites = all_websites()
        for i in range(len(my_websites)):
            if my_websites[i] in content:
                new_content = content.replace(my_websites[i], "")
                host.truncate(0)
                host.write(new_content)
            else:
                print(i + " has not been blocked")

if __name__ == "__main__":
    menu_driven = int(input("1. Block a website, 2. Unblock a Website: "))
    if menu_driven == 1:
        blocker()
    elif menu_driven == 2:
        unblocker()
    else:
        print("Enter either 1 or 2")

Testing the script

First, let’s see what’s in our host file right now. We can see there is copyright stuff, but since they are commented on, they are not required, so we don’t have to worry about the initial content at all.

testing the script

I will use the website python.org in this blog as an example. Let’s run our program first.

running Website Blocker python program

We want to block it at first. But before that, let’s see if it is working in the browser.

python.org website

Since it is working, let’s block it now.

entering url

The program has now blocked the website. Let’s check the host file in the browser.

entering ip address

It has been added to the host file. But, lets see if it works in the browser.

website blocked

You can see that the website has now been blocked.

Now, let’s unblock it. So, run the python script again.

running Website Blocker python program again
running Website Blocker python program again 2

The program has now unblocked the website. Let’s check the host file.

website removed

It has now been removed from the host file. But, does it work in the browser, let’s check.

python.org unblocked

You can see that it now works in the browser too.

Congratulations, you have successfully created a Website Blocker Using Python that allows you to block and unblock a website on Windows. You can make this script even better by making a Graphical User Interface out of it using Tkinter.


Also Read:

Share:

Author: Ayush Purawr