Skip to content

Commit 684d4ad

Browse files
Merge pull request prathimacode-hub#328 from Rutuj-Runwal/WebsiteBlocker
Added Website Blocker
2 parents 091b542 + 234db5a commit 684d4ad

File tree

6 files changed

+163
-0
lines changed

6 files changed

+163
-0
lines changed
20.9 KB
Loading
Loading
29.2 KB
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# <p align = "center"> Website Blocker using PC Hosts files </p>
2+
## Introduction:
3+
This is a script that aims to implement a website blocking utility for Windows-based systems. It makes use of the computer's hosts files and runs it as a background process, preventing access to the sites entered by the user in list format.
4+
## Third-party libraries required:
5+
The project does not require any third party libraries
6+
7+
## Running the Script:
8+
After opening the script in your Python IDE, execute the code so that you get the UI output window. Open your browser and try to visit the websites you blocked. When the script runs successfully, you will see `This site can't be reached` error or similar 404 error's on the browser.
9+
10+
**Note:**
11+
> In some systems, access to the computers's hosts files maybe denied by default to prevent malware attacks. So the script while executing may show an error while modifying the hosts files.
12+
> Please visit [here](https://www.technipages.com/windows-access-denied-when-modifying-hosts-or-lmhosts-file) for a brief readup on how to solve the issue.
13+
14+
> *Recommended:* Please revert to the original access settings after testing the script to prevent any future compromise
15+
16+
## Output:
17+
#### The output UI will appear as shown below:
18+
![Output 1](./Images/UI1.png)
19+
#### You can add new site as shown below then click on "Add Website" button.You can add as many as you want:
20+
![Output 2](./Images/UI2.png)
21+
#### If you entered anything that's not a proper website. An error will show up to guide you:
22+
![Output 3](./Images/UI3.png)
23+
24+
#### Once you are done with adding websites, you can click on Block-Sites button to begin blocking
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
os
2+
shell
3+
sys
4+
ctypes
5+
time
6+
datetime
7+
tkinter
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import win32com.shell.shell as shell
2+
import os
3+
import sys
4+
import ctypes
5+
import time
6+
from datetime import datetime as dt
7+
from tkinter import *
8+
from tkinter import messagebox
9+
10+
#Create tkinter root/GUI
11+
root = Tk()
12+
root.title("Website Blocker by Rutuj Runwal")
13+
root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
14+
root.geometry("600x300")
15+
ASADMIN = 'asadmin'
16+
# Host's Path - All the website info that is to be blocked is saved here
17+
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
18+
# localhost's IP
19+
redirect = "127.0.0.1"
20+
website_list = []
21+
22+
23+
def AddWebsite():
24+
site = Input.get() # Get the site-input given by the user and check if it is
25+
print("You Entered: "+site)
26+
if("www" not in site or "." not in site):
27+
messagebox.showinfo(
28+
"Invalid Website", "Make sure the site is of this format 'www.google.com' `")
29+
else:
30+
website_list.append(site)
31+
print(website_list)
32+
33+
# Function to check for admin access
34+
def is_admin():
35+
try:
36+
return ctypes.windll.shell32.IsUserAnAdmin()
37+
except:
38+
return False
39+
40+
41+
def Block():
42+
if is_admin():
43+
while True:
44+
# Time of your work
45+
if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 16):
46+
print("Access Denied")
47+
with open(hosts_path, 'r+') as file:
48+
content = file.read()
49+
for website in website_list:
50+
if website in content:
51+
pass
52+
else:
53+
# Mapping hostnames to your localhost IP address
54+
file.write(redirect + " " + website + "\n")
55+
else:
56+
with open(hosts_path, 'r+') as file:
57+
content = file.readlines()
58+
file.seek(0)
59+
for line in content:
60+
if not any(website in line for website in website_list):
61+
file.write(line)
62+
# Removing hostnames from host file
63+
file.truncate()
64+
65+
print("Access Granted")
66+
time.sleep(5)
67+
else:
68+
# Retry getting admin access to modify hosts file
69+
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
70+
if is_admin():
71+
while True:
72+
# Time of your work
73+
if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 16):
74+
print("Access Denied")
75+
with open(hosts_path, 'r+') as file:
76+
content = file.read()
77+
for website in website_list:
78+
if website in content:
79+
pass
80+
else:
81+
# mapping hostnames to your localhost IP address
82+
file.write(redirect + " " + website + "\n")
83+
else:
84+
with open(hosts_path, 'r+') as file:
85+
content = file.readlines()
86+
file.seek(0)
87+
for line in content:
88+
if not any(website in line for website in website_list):
89+
file.write(line)
90+
# removing hostnames from host file
91+
file.truncate()
92+
93+
print("Access Granted")
94+
time.sleep(5)
95+
96+
# The BlockSites function is used to handle no. of sites to block
97+
def BlockSites():
98+
if(len(website_list) == 1):
99+
Val = messagebox.askquestion("", "You are about to block 1 website.Are you sure you dont want to add more?")
100+
if Val == "yes": #If user says "yes" , block the site provided
101+
print("Blocking One Site...")
102+
Block()
103+
else:
104+
messagebox.showinfo("", "Add more sites and then press Block-Sites when you are ready")
105+
if(len(website_list) == 0):
106+
#If the website_list is zero it means the user has not added any site to block
107+
messagebox.showinfo("No sites to block","Please add sites to block first!")
108+
else:
109+
#If the sites are >1 block them directly
110+
print("Ready to block "+str(len(website_list)) + " sites")
111+
Block()
112+
113+
114+
if sys.argv[-1] != ASADMIN:
115+
script = os.path.abspath(sys.argv[0])
116+
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
117+
try:
118+
# Try running the code with admin access
119+
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
120+
messagebox.showinfo("Welcome", "Welcome to Website Blocker v1.0.Add Websites to block,Once you are done click on Block-Sites to get started!")
121+
MyLabel = Label(root, text="Enter Website to Block:")
122+
MyLabel.grid(row=0, column=0)
123+
Input = Entry(root, width=60, borderwidth=3)
124+
Input.insert(0, "Please REMOVE this text and enter website address.")
125+
Input.grid(row=0, column=2)
126+
MyBtn = Button(root, text="Add Website",command=AddWebsite).grid(row=1, column=2)
127+
MyBtn2 = Button(root, text="Block-Sites",command=BlockSites).grid(row=3, column=2)
128+
root.mainloop()
129+
except(Exception):
130+
# Show an error when admin access is denied
131+
messagebox.showerror(
132+
"ERR:Admin Denied", "Admin rights are required for the script to work")

0 commit comments

Comments
 (0)