Python Script to Block or Unblock Websites with Full Source Code For Beginners

This script lets you block websites on your computer by editing your host’s file.

Usage

  • First, add your Blocked Websites to the array in both scripts.
  • On Linux: 
sudo python website_blocker.pyCode language: CSS (css)
  • On Windows, run the script as Administrator
  • To unblock the websites, run the  script.
website_unblocker.pyCode language: CSS (css)

Source Code:

website_blocker.py

import platform

if platform.system() == "Windows":
        pathToHosts=r"C:\Windows\System32\drivers\etc\hosts"
elif platform.system() == "Linux":
        pathToHosts=r"/etc/hosts"

redirect="127.0.0.1"
websites=["https://www.sislovesme.com/","https://motherless.com/","https://xhamster.com/","https://www.xnxx.com/","https://www.xvideos.com/","https://www.pornhub.com/"]

with open(pathToHosts,'r+') as file:
    content=file.read()
    for site in websites:
        if site in content:
            pass
        else:
            file.write(redirect+" "+site+"\n")Code language: JavaScript (javascript)

website_unblocker.py 

import platform

if platform.system() == "Windows":
        pathToHosts=r"C:\Windows\System32\drivers\etc\hosts"
elif platform.system() == "Linux":
        pathToHosts=r"/etc/hosts"

websites=["https://www.sislovesme.com/","https://motherless.com/","https://xhamster.com/","https://www.xnxx.com/","https://www.xvideos.com/","https://www.pornhub.com/"]

with open(pathToHosts,'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()Code language: JavaScript (javascript)

Leave a Comment