【发布时间】:2019-05-08 21:24:45
【问题描述】:
所以我在尝试以管理员身份运行此 python 代码时遇到问题,因此我无法访问和写入主机文件。谁能帮我?我查看了许多其他问题,但似乎没有一个有效。
主机文件目录: C:\Windows\System32\Drivers\etc\hosts
(如) Request UAC elevation from within a Python script?
其中一些答案实际上适用于提示获得管理员访问权限,但它仍然没有授予我的程序权限。我想出的唯一方法是先以管理员身份运行 python shell,然后以管理员身份运行代码或运行命令提示符,然后使用命令提示符打开 python 文件。
网站
https://boostlog.io/@faisalnad/create-a-website-blocker-with-python-5afe86ff47018500491f4898
这个程序是为阻止网站而设计的。
import time
from datetime import datetime as dt
# change hosts path according to your OS
hosts_path = r”C:\Windows\System32\Drivers\etc\hosts”
# localhost's IP
redirect = "127.0.0.1"
# websites That you want to block
website_list = ["www.facebook.com","facebook.com",
"dub119.mail.live.com","www.dub119.mail.live.com",
"www.gmail.com","gmail.com"]
while True:
# time of your work
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):
print("Working hours...")
with open(hosts_path, 'r+') as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
# mapping hostnames to your localhost IP address
file.write(redirect + " " + website + "\n")
else:
with open(hosts_path, 'r+') as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in website_list):
file.write(line)
# removing hostnmes from host file
file.truncate()
print("Fun hours...")
time.sleep(5)
这是错误:
Working hours...
Traceback (most recent call last):
File "C:\Users\Key\Desktop\random project.py", line 19, in <module>
with open(hosts_path, 'r+') as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\Drivers\\etc\\hosts'
【问题讨论】:
-
检查 AV 是否正在运行,它可能锁定了
hosts文件,还要确保脚本以特权运行。注意:hosts_path似乎是硬编码的,c并不总是默认的操作系统安装驱动器。请记住在更改主机文件后发出ipconfig /flushdns。这个项目看起来很有趣!阻止学生在学习时间访问社交媒体?!太棒了!
标签: python python-3.x host