Category: Python Web Blocker

  • Script Deployment on Windows

    This section of the tutorial illustrates how the python script will be deployed at start-up so that we don’t need to open the terminal all the time to run the script.

    Steps for Script Deployment on Windows

    If we want to script deployment on Windows, we have to follow these steps:

    Changing the Hosts File Path on Windows

    Lets first change our hosts file path from “/etc/hosts” to “C:\System32\drivers\etc\hosts” as the hosts file is stored at this location on windows.

    Opening Windows Task Scheduler

    If we want to schedule the tasks on the windows, we need to open the task scheduler as shown in the below image.

    Script Deployment on Windows

    Creating a New Task

    Click on Create Task.. given in the right pane of the application.

    The following window will open.

    Script Deployment on Windows

    Configuring Task Properties

    Configure the properties and give the name and other required properties for your script. Do check the Checkbox as “Run with highest privileges“.

    Script Deployment on Windows

    Setting the Startup Trigger

    Go to Triggers and create a new trigger as shown in the below image.

    Select the “At startup” option from the drop-down list so that the script can run at start-up.

    Script Deployment on Windows

    Adding Script Action

    Now, go to Actions and create a new action by clicking on new.

    Script Deployment on Windows


    The following window will open. Select the “Start a program” action from the drop-down list and browse the path to the script, i.e. blocker.py (in my case it is E:\blocker.py) and click OK.

    Script Deployment on Windows

    Configuring Task Conditions

    Now, click on Conditions and deselect the 2nd option which says “Start the task only if the computer is on AC power.

    Script Deployment on Windows

    Final Task Settings

    Now, go to settings and click OK as shown in the following image.

    Script Deployment on Windows

    Verifying the Scheduled Task

    Now, we got our task Website-blocker scheduled at system start-up. We can check this in the task list as shown in the following image.

    Script Deployment on Windows

    Restarting and Testing the Script

    Now, we need to restart our system to make the script active on system start-up.

    Restart the system now, and try to access the blocked website www.facebook.com as we are in working hours now.

    It will show the display which looks like following.

    Script Deployment on Windows

    Conclusion

    Hence, we have got our script working fine on system start-up and block the access to www.facebook.com (or any website you want) automatically.

  • Script deployment on Linux

    Hence, we are done with the python script (blocker.py) which is running fine. This is the time to deploy this script at system startup.

    The process to deploy a script to run at startup depends upon the operating system. In this section of the tutorial, we will describe the process for Linux and windows.

    Procedure

    If we want to schedule a script to run at startup on Linux, we need to configure the entry in the crontab schedule.

    The crontab can be defined as the list that contains the commands that are to be run on a regular schedule. The crontab stands for cron table which is a set schedule according to which the script is executed on a regular interval.

    Steps for Script deployment on Linux

    Follow the following steps.

    Step 1:

    Open the crontab with the -e flag. Run the following command on the terminal on Linux.

    $ sudo crontab -e   
    

    This will open a crontab file which looks like following.

    Script deployment on Linux

    Step 2:

    Now add the following line to the file and save it.

    @reboot python3 /home/javatpoint/Desktop/Python/website_blocker/blocker.py  
    
    Script deployment on Linux

    Step 3:

    Restart the system now. On reboot, our script blocker.py is scheduled to run at system start-up. As of now, we are in working hours. So let’s try to open the Facebook on the browser.

    Script deployment on Linux

    As shown in the above image, the website www.facebook.com is refused to connect. Hence, our script is working fine on the system start-up as the website is refused to connect.

  • Building python script

    Let’s start building the python script that can run at system startup to block the access to the particular websites. Open PyCharm to edit the code or you can use any IDE you want.

    Create a new Python Script named as web-blocker.py. To make the process understandable to you, we will build this script step by step. So let’s start coding by setting up all the required variables.

    Setting up the variables

    This step initializes all the required variables that will be used in the script. Here, the host_path is set to the path to the hosts file. In our case, it is located under /etc. In python, r is used to represent the raw string.

    The redirect is assigned to the localhost address, i.e. 127.0.0.1. The websites is a list which contains the website lists that are to be blocked.

    host_path = r"/etc/hosts"  
    redirect = "127.0.0.1"  
    websites = ["www.facebook.com", "https://www.facebook.com"]  

    Setting up the infinite loop

    We need to have a while loop in the python script to make sure that our script will run at every 5 seconds.

    To make this happen, we will use the sleep() method of the time module.

    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

    In the process to build our desired python script, we need to check the current time whether it is working time or fun time since the application will block the website access during the working time.

    To check the current time, we will use the datetime module. We will check whether the datetime.now() is greater than the datetime object for 9 AM of the current date and is lesser than the datetime object for 5 PM of the current date.

    Let’s discuss more the output of datetime.now().

    Building python script

    It returns a datetime object containing current time including year (2019), month(January 1st), date(23rd), time (hour, minutes, seconds). We can compare this value and check whether this value exists between the 9 AM for the current date and 5 PM for a current date using if statement.

    The script will now contain the following code.

    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 main objective of the script is to keep modifying the hosts file at regular intervals. To let the script configure the hosts file, we need to implement the file handling methods here.

    The following code is added to the hosts file.

    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() method opens the file stored as host_path in r+ mode. First of all, we read all the content of the file by using the read() method and store it to a variable named content.

    The for loop iterates over the website list (websites) and we will check for each item of the list whether it is already present in the content.

    If it is present in the hosts file content, then we must pass. Otherwise, we must write the redirect-website mapping to the hosts file so that the website hostname will be redirected to the localhost.

    The hosts file will now contain the following python code.

    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)  

    Now, let’s run this python script and check whether it has modified the hosts file or not.

    Building python script

    As we can see, It keeps printing working hours on the console as we are in working hours. Now, let’s check the content of the hosts file.

    Building python script

    As we can see, the two lines have been added to the hosts file. It will redirect the access of Facebook to the localhost.

    Removing from the hosts file

    Our script is working fine for the working hours, now lets add some features for the fun hours also. In the fun hours (not working hours) we must remove the added lines from the hosts file so that the access to the blocked websites will be granted.

    The following code is added to the else part (fun hours case) of the script.

    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 part will be executed during the fun hours, and it removes all the mappings that block the access to some specific websites on the computer.

    Let’s check the content of hosts file on the execution of the python script during the fun hours.

    Building python script

    The final script

    Now, we have a python script which is running fine to block the access of some particular websites during working hours (9 AM to 5 PM) and provide the access during the fun hours.

    The script web-blocker.py is given below.

    web-blocker.py
    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)  
  • Python Website Blocker

    In this section of the tutorial, we are going to build a real-time most popular python application known as website blocker. This application can be used to block the websites so that the user can not open them during the specific period.

    Let’s discuss how can we build such an application by using python.

    Objective

    The objective of Python website blocker is to block some certain websites which can distract the user during the specified amount of time. In this application, we will block the access to the list of some particular websites during the working hours so that the user can only access those websites during the free time only.

    The working time in this python application is considered from 9 AM to 5 PM. The time period except that time will be considered as free time.

    Process

    If we want to block the access to a specific website on the computer, we need to configure the hosts file.

    The hosts file

    The hosts file is a local file which was used to map hostnames to IP addresses in the old days. Although the DNS service is used nowadays to map the hostnames to the IP addresses, the host file is still very complex and can be used to configure the mapping of the IP addresses locally.

    Location of hosts file

    The location of the hosts file varies from operating system to operating system.

    Windows: C:\Windows\System32\drivers\etc

    mac and Linux: /etc/hosts

    Configuration

    Since the hosts file contains the mapping between the host names and IP addresses, let’s look at the content of our hosts file first stored as /etc/hosts as we use CentOS 7 (Linux).

    Python Website Blocker

    As we can see in the above image, the mappings are saved for the localhost with the IP address 127.0.0.1.

    Similarly, we can redirect any hostname back to the localhost IP (127.0.0.1). It will block the access to that hostname and redirect that to localhost on each request.

    For testimony, let’s edit the content of hosts file and add some of the following lines to it. If we want to make changes to the /etc/hosts file, we will need to change its permissions.

    Run the following command on the terminal to change the permissions.

    Command:

    $ sudo chmod 777 /etc/hosts   

    Now add the following line to the file to block the access to facebook.com (for example).

    127.0.0.1       www.facebook.com   

    As shown in the image below.

    Python Website Blocker

    Save the file and try to open the www.facebook.com using the browser.

    Python Website Blocker

    As shown in the above figure, it is refused to connect.

    We have completed our task by manually editing the hosts file. We haven’t achieved our objective yet. Our objective is to block access to some particular websites (for example, facebook) during working hours only (9 AM to 5 PM).

    It needs a python script which keeps adding the necessary lines to the hosts file during a particular period.

    In this section of the tutorial, we will build such python script which keeps editing the hosts file during the working hours. We will also deploy that script at the OS startup so that it doesn’t need any external execution.

    Requirements

    We need to know the following python modules to build the python website blocker.

    1. file handling: file handling is used to do the modifications to the hosts file.
    2. time: The time module is used to control the frequency of the modifications to the hosts file.
    3. datetime: The datetime module is used to keep track of the free time and working time.