How to Build Python Script

Let’s begin creating a Python script capable of executing at system startup to restrict access to specific websites. Launch PyCharm to modify the code, or feel free to utilize any integrated development environment (IDE) of your choice.

Initiate a new Python script titled web-blocker.py. To facilitate your comprehension of the process, we will construct this script incrementally. Thus, let us commence the coding by establishing all the necessary variables.

Setting up the variables

This stage involves the initialization of all essential variables that will be utilized throughout the script. In this instance, the variable host_path is assigned the location of the hosts file. Specifically, it can be found in the /etc directory. In Python, the prefix r denotes a raw string.

The redirection is designated to the localhost IP address, specifically 127.0.0.1. The term "websites" refers to a collection that includes the list of websites intended for blocking.

Example

host_path = r"/etc/hosts"

redirect = "127.0.0.1"

websites = ["www.facebook.com", "https://www.facebook.com"]

Setting up the infinite loop

In our Python script, it is essential to implement a while loop to ensure that the execution occurs every 5 seconds.

To achieve this, we will utilize the sleep function from the time module.

Example

import time

host_path = r"/etc/hosts"

redirect = "127.0.0.1"

websites = ["www.facebook.com", "https://www.facebook.com"]

while True:

    time.sleep(5)

Determining the time

As we work on developing our intended Python script, it is essential to verify the current time to determine whether it falls under working hours or leisure hours. This is important because the application is designed to restrict access to websites during designated working times.

To verify the current time, we will utilize the datetime module. We will determine if the result of datetime.now exceeds the datetime object representing 9 AM of today and if it is also less than the datetime object for 5 PM of the same day.

Let's discuss more the output of datetime.now.

It provides a datetime object that encompasses the current time, which includes the year (2019), month (January 1st), date (23rd), and time (hour, minutes, seconds). We can evaluate this value and determine if it falls between 9 AM and 5 PM for the current date by utilizing an if statement.

The script will now contain the following code.

Example

from time import *

from datetime import *

host_path = r"/etc/hosts"

redirect = "127.0.0.1"

websites = ["www.facebook.com", "https://www.facebook.com"]

while True:

    if datetime(datetime.now().year,datetime.now().month,datetime.now().day,9)< datetime.now()< datetime(datetime.now().year,datetime.now().month,datetime.now().day,17):

        print("Working hours")

    else:

        print("Fun hours")

    sleep(5)

Writing to the hosts file

The primary goal of the script is to continuously update the hosts file at specified intervals. In order for the script to effectively manage the hosts file, it is essential to incorporate file handling techniques in this section.

The following code is added to the hosts file.

Example

with open(host_path,"r+") as fileptr:

            content = fileptr.read()

            for website in websites:

                if website in content:

                    pass

                else:

                    fileptr.write(redirect+"

					"+website+"\n")

The open function is utilized to access the file located at host_path in r+ mode. Initially, we retrieve the entire contents of the file by employing the read method and assign it to a variable called content.

The for loop traverses through the list of websites (websites), where we will verify if each element in the list is already included in the content.

If the content of the hosts file includes it, then we can proceed. If it is not found, we need to add the redirect-website mapping to the hosts file, ensuring that the hostname of the website is redirected to the localhost.

The hosts file will subsequently include the following Python code.

Example

from time import *

from datetime import *

host_path = r"/etc/hosts"

redirect = "127.0.0.1"

websites = ["www.facebook.com", "https://www.facebook.com"]

while True:

    if datetime(datetime.now().year,datetime.now().month,datetime.now().day,9)<datetime.now()<datetime(datetime.now().year,datetime.now().month,datetime.now().day,17):

        print("working hours")

        with open(host_path,"r+") as fileptr:

            content = fileptr.read()

            for website in websites:

                if website in content:

                    pass

                else:

                    fileptr.write(redirect+"    "+website+"\n")

    else:

        print("Fun hours")

    sleep(5)

At this point, we will execute the Python script to verify if it has successfully altered the hosts file.

As observed, it continues to output the working hours to the console since we are currently within those hours. Next, let's examine the contents of the hosts file.

As observed, two entries have been incorporated into the hosts file. This will reroute any attempts to access Facebook to the localhost.

Removing from the hosts file

Our script is currently functioning well during regular working hours; however, let's enhance it by incorporating features for the non-working hours as well. During these fun hours (when working hours are not in effect), it is necessary to eliminate the lines that were previously added to the hosts file, thereby allowing access to the previously blocked websites.

The subsequent code snippet is integrated into the else section (the fun hours scenario) of the script.

Example

with open(host_path,'r+') as file:

    content = file.readlines();

    file.seek(0)

    for line in content:

        if not any(website in line for website in		websites):

            file.write(line)

    file.truncate()

print("fun hours")

The else section will be triggered during the enjoyable hours, and it eliminates all the mappings that hinder access to certain designated websites on the computer.

Let’s examine the contents of the hosts file while executing the Python script during the enjoyable hours.

The final script

At this point, we possess a Python script that functions effectively to restrict access to specific websites during designated working hours, which are from 9 AM to 5 PM, while allowing access during leisure hours.

The script web-blocker.py is given below.

web-blocker.py

Example

from time import *

from datetime import *

host_path = r"/etc/hosts"

redirect = "127.0.0.1"

websites = ["www.facebook.com", "https://www.facebook.com"]

while True:

    if datetime(datetime.now().year,datetime.now().month,datetime.now().day,9)<datetime.now()<datetime(datetime.now().year,datetime.now().month,datetime.now().day,17):

        with open(host_path,"r+") as fileptr:

            content = fileptr.read()

            for website in websites:

                if website in content:

                    pass

                else:

                    fileptr.write(redirect+"    	"+website+"\n")

    else:

        with open(host_path,'r+') as file:

            content = file.readlines();

            file.seek(0)

            for line in content:

                if not any(website in line for website in 				websites):

                    file.write(line)

            file.truncate()

    sleep(5)

Input Required

This code uses input(). Please provide values below: