运行网站拦截Python代码时遭遇PermissionError权限拒绝问题求助
解决Windows下修改hosts文件的PermissionError问题
问题场景
运行以下网站拦截Python代码时,出现PermissionError: [Errno 13] Permission denied错误,无法修改Windows系统的hosts文件:
import datetime import time end_time=datetime.datetime(2022,9,22) site_block=["www.wscubetech.com","www.facebook.com"] host_path="C:/Windows/System32/drivers/etc/hosts" redirect="127.0.0.1" while True: if datetime.datetime.now()<end_time: print("Start Blocking..") with open(host_path,"r+") as host_file: content = host_file.read() for website in site_block: if website not in content: host_file.write(redirect+" "+website+"\n") else: pass else: with open(host_path,"r+") as host_file: content = host_file.readlines() host_file.seek(0) for lines in content: if not any(website in lines for website in site_block): host_file.write(lines) host_file.truncate() time.sleep(5)
错误信息:
PermissionError Traceback (most recent call last) Input In [15], in <cell line: 8>() 9 if datetime.datetime.now()<end_time: 10 print("Start Blocking..") ---> 11 with open(host_path,"r+") as host_file: 12 content = host_file.read() 13 for website in site_block: PermissionError: [Errno 13] Permission denied: 'C:/Windows/System32/drivers/etc/hosts'
解决方案
以管理员身份启动Jupyter Notebook
在开始菜单找到Jupyter Notebook图标,右键选择「以管理员身份运行」,之后打开目标笔记本重新执行代码。Windows系统的hosts属于受保护的系统文件,必须拥有管理员权限才能修改。修改hosts文件的权限设置
- 定位到
C:\Windows\System32\drivers\etc\hosts文件,右键点击选择「属性」 - 切换到「安全」选项卡,点击「编辑」按钮
- 在权限列表中找到当前登录的用户账户,勾选「写入」权限,点击「确定」保存设置。之后无需管理员权限即可修改该文件。
- 定位到
保存为脚本,用管理员命令行运行
- 将代码保存为
site_blocker.py文件 - 按下Win+X组合键,选择「Windows终端(管理员)」或「命令提示符(管理员)」
- 切换到脚本所在目录,执行命令:
python site_blocker.py
- 将代码保存为
额外提示
代码中的end_time设置为2022,9,22,当前时间已远超过该日期,代码会持续执行解除拦截的逻辑。如果需要测试网站拦截功能,建议将end_time修改为未来的日期,例如:
end_time=datetime.datetime(2025, 12, 31)
内容的提问来源于stack exchange,提问作者user20017494
相关产品推荐
相关产品推荐

