无法访问“C:\Windows\System32\Drivers\etc\hosts”,权限被拒绝。

4

我有一个问题,想以管理员身份运行这个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不总是默认的操作系统安装驱动器。在更改 hosts 文件后记得发出 ipconfig /flushdns 命令。这个项目看起来很有趣!在学习时间阻止学生访问社交媒体?太棒了! - Pedro Lobito
1个回答

0

您可以通过以下链接为您的程序运行用户添加写入权限,以添加主机文件的权限。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接