首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PermissionError:[Errno 13]权限被拒绝:‘C:/Windows/System32 32/drivers/etc/host

PermissionError:[Errno 13]权限被拒绝:‘C:/Windows/System32 32/drivers/etc/host
EN

Stack Overflow用户
提问于 2022-09-22 05:38:30
回答 2查看 527关注 0票数 0

这是用于网站阻塞的Python代码。我正在使用木星笔记本运行这段代码。当我运行这个程序时,我会得到错误名为PermissionError。

代码语言:javascript
复制
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)

这是我在运行这个程序时遇到的错误:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2022-09-22 05:49:57

拒绝权限仅仅意味着系统没有权限打开该文件夹的文件。

C:\Windows\System32\drivers\etc\hosts只能由管理员写。您应该在管理员模式下运行脚本。

编辑(23/09/2022 -注释):

I在管理员模式下运行您的代码,没有错误,也没有输出,但是文件被修改了(然后删除了两行):

我重写了测试代码。这里是一种不同的方法:

代码语言:javascript
复制
site_block = ["www.facebook.com", "www.stackoverflow.com"]
host_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"
with open(host_path, "r+") as host_file:
    for website in filter(lambda website: website not in host_file.read(), site_block):
        host_file.write(redirect + " " + website + "\n")

time.sleep(5)

with open(host_path, "r") as host_file:
    lines = host_file.readlines()
    with open(host_path, "w") as output:
        for line in lines:
            if not any(redirect + " " + website + "\n" == line for website in site_block):
                output.write(line)

提示:

  • 您可以使用布尔值来知道是否已经更新了文件,以避免每5秒打开一次。
  • 您可以在清理文件之后停止进程。
  • 也可以使用cron.

运行代码。

票数 1
EN

Stack Overflow用户

发布于 2022-09-22 05:49:05

当您没有做某事的权限时,就会导致PermissionError。文件C:/Windows/System32 32/驱动器/etc/host受权限保护。这就是为什么你不能访问它。为什么不以管理员的身份运行它呢?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73809788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档