Skip to content

Commit 9d867b6

Browse files
committed
Add website blocker tutorial code
1 parent d53deb6 commit 9d867b6

1 file changed

Lines changed: 146 additions & 0 deletions

File tree

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Website Blocker — Block distracting websites by modifying the hosts file.
4+
5+
This script adds entries to your system's hosts file to redirect
6+
specified websites to 127.0.0.1 (localhost), effectively blocking them.
7+
8+
Usage:
9+
sudo python website_blocker.py block # Block all sites
10+
sudo python website_blocker.py unblock # Unblock all sites
11+
python website_blocker.py status # Show blocked sites
12+
"""
13+
14+
import sys
15+
import platform
16+
17+
# ============================================================
18+
# CONFIGURATION — edit this list to block different sites
19+
# ============================================================
20+
21+
SITES_TO_BLOCK = [
22+
# Social media
23+
"www.facebook.com", "facebook.com",
24+
"www.twitter.com", "twitter.com",
25+
"www.instagram.com", "instagram.com",
26+
"www.reddit.com", "reddit.com",
27+
# Video / entertainment
28+
"www.youtube.com", "youtube.com",
29+
"www.tiktok.com", "tiktok.com",
30+
"www.twitch.tv", "twitch.tv",
31+
]
32+
33+
REDIRECT_IP = "127.0.0.1"
34+
35+
# Markers keep our entries isolated so we never touch
36+
# other entries in the hosts file.
37+
START_MARKER = "# >>> WEBSITE BLOCKER START >>>"
38+
END_MARKER = "# <<< WEBSITE BLOCKER END <<<"
39+
40+
# ============================================================
41+
# Cross‑platform hosts path
42+
# ============================================================
43+
44+
def get_hosts_path():
45+
"""Return the absolute path to the hosts file for this OS."""
46+
system = platform.system()
47+
if system == "Windows":
48+
return r"C:\Windows\System32\drivers\etc\hosts"
49+
# macOS and Linux both use /etc/hosts
50+
return "/etc/hosts"
51+
52+
HOSTS_PATH = get_hosts_path()
53+
54+
# ============================================================
55+
# Core operations
56+
# ============================================================
57+
58+
def block_websites():
59+
"""Write (or refresh) the blocker block into the hosts file."""
60+
# Read the current file
61+
with open(HOSTS_PATH, "r") as fh:
62+
content = fh.read()
63+
64+
# Strip any previous block so we start fresh
65+
if START_MARKER in content:
66+
content = content.split(START_MARKER)[0].rstrip("\n") + "\n"
67+
68+
# Build the block
69+
block_lines = [START_MARKER + "\n"]
70+
for site in SITES_TO_BLOCK:
71+
block_lines.append(f"{REDIRECT_IP}\t{site}\n")
72+
block_lines.append(END_MARKER + "\n")
73+
74+
# Write everything back
75+
with open(HOSTS_PATH, "w") as fh:
76+
fh.write(content)
77+
fh.writelines(block_lines)
78+
79+
unique_sites = len(SITES_TO_BLOCK) // 2
80+
print(f"[+] Blocked {unique_sites} websites "
81+
f"({len(SITES_TO_BLOCK)} URLs) → {REDIRECT_IP}")
82+
83+
84+
def unblock_websites():
85+
"""Remove the blocker block from the hosts file."""
86+
with open(HOSTS_PATH, "r") as fh:
87+
content = fh.read()
88+
89+
if START_MARKER not in content:
90+
print("[*] No websites are currently blocked.")
91+
return
92+
93+
# Cut out the marked section
94+
before = content.split(START_MARKER)[0].rstrip("\n")
95+
after = content.split(END_MARKER)[-1]
96+
new_content = before + "\n" + after.lstrip("\n")
97+
98+
with open(HOSTS_PATH, "w") as fh:
99+
fh.write(new_content)
100+
101+
print("[+] All websites unblocked. Focus mode off.")
102+
103+
104+
def show_status():
105+
"""Print which websites are currently blocked."""
106+
with open(HOSTS_PATH, "r") as fh:
107+
content = fh.read()
108+
109+
if START_MARKER not in content:
110+
print("[*] No websites are currently blocked.")
111+
return
112+
113+
block = content.split(START_MARKER)[1].split(END_MARKER)[0]
114+
sites = [line.strip() for line in block.split("\n")
115+
if line.strip() and not line.strip().startswith("#")]
116+
117+
print(f"[*] {len(sites)} URLs currently blocked → {REDIRECT_IP}:")
118+
for site in sites:
119+
print(f" {site.split()[-1]}")
120+
121+
122+
# ============================================================
123+
# CLI entry point
124+
# ============================================================
125+
126+
if __name__ == "__main__":
127+
if len(sys.argv) < 2:
128+
print("Website Blocker — block distracting sites via /etc/hosts\n")
129+
print("Usage:")
130+
print(" sudo python website_blocker.py block")
131+
print(" sudo python website_blocker.py unblock")
132+
print(" python website_blocker.py status")
133+
sys.exit(1)
134+
135+
command = sys.argv[1].lower()
136+
137+
if command == "block":
138+
block_websites()
139+
elif command == "unblock":
140+
unblock_websites()
141+
elif command == "status":
142+
show_status()
143+
else:
144+
print(f"[!] Unknown command: {command}")
145+
print("Valid commands: block, unblock, status")
146+
sys.exit(1)

0 commit comments

Comments
 (0)