website blocker python

Solutions on MaxInterview for website blocker python by the best coders in the world

showing results for - "website blocker python"
Angel
20 Apr 2016
1#Import libraries
2import time
3from datetime import datetime as dt
4#Windows host file path
5hostsPath=r"C:\Windows\System32\drivers\etc\hosts"
6redirect="127.0.0.1"
7#Add the website you want to block, in this list
8websites=["www.youtube.com","youtube.com", "www.facebook.com", "facebook.com"]
9while True:
10   #Duration during which, website blocker will work
11   if dt(dt.now().year,dt.now().month,dt.now().day,9) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,18):
12   print ("Sorry Not Allowed...")
13   with open(hostsPath,'r+') as file:
14      content = file.read()
15      for site in websites:
16         if site in content:
17            pass
18         else:
19            file.write(redirect+" "+site+"\n")
20   else:
21      with open(hostsPath,'r+') as file:
22      content = file.readlines()
23      file.seek(0)
24      for line in content:
25         if not any(site in line for site in websites):
26            file.write(line)
27         file.truncate()
28   print ("Allowed access!")
29time.sleep(5)