我正在尝试编写一个 python 脚本,它可以根据一天中的时间阻止网站,但我无法在 Windows 中编辑主机文件,即使以管理员身份运行 cmd 也是如此。
这是代码:
import time
from datetime import datetime as dt
hosts_location=r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp="hosts"
blocked_websites=['www.facebook.com','facebook.com']
redirect="127.0.0.1"
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,8) < dt.now() <
dt(dt.now().year,dt.now().month,dt.now().day,17):
with open(hosts_location,"r+") as file:
content=file.read()
for website in blocked_websites:
if website in content:
pass
else:
file.write(redirect+"\t"+website+"\n")
print("Working Hours....")
else:
with open(hosts_location,"r+") as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in blocked_websites):
file.write(line)
file.truncate()
print("Fun Time...")
time.sleep(5)
更新:该代码对于本地主机文件运行良好,但是当我尝试将其用于真正的主机文件时,即使作为管理员,脚本也会闪烁,并且 cmd 显示消息“[Errno 13]:权限被拒绝”。
此外,即使使用记事本,我也无法编辑主机,即使作为管理员,我的操作系统是 Windows 10 家庭版 64 位。
首先,
如果您不是管理员,请通过以下方式更改主机文件的权限右键-->属性-->安全并允许读/写/执行权限Users.
Then 以管理员身份打开命令提示符并运行脚本。它会起作用的!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)