【问题标题】:Unable to edit hosts file with python无法使用 python 编辑主机文件
【发布时间】:2017-08-18 14:13:39
【问题描述】:

我正在尝试编写一个 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]:Permission Denied”。 即使管理员我的操作系统是 Windows 10 家庭版 64 位,我也无法使用记事本编辑主机。

【问题讨论】:

  • 你得到的错误是什么?
  • 那么所有的dt.now().something 电话是怎么回事?
  • 你的缩进也关闭了。在while True: 之后,所有内容都应该缩进,这可能是导致您的问题的原因
  • 我没有运行这个确切的代码(因为我不希望我的主机文件被完全破坏),但我无法重现您的问题。也许您应该详细说明您认为无法修改文件的原因(是否会引发异常?)。
  • 即使以管理员身份运行 cmd 也会出现此错误: PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\drivers\\etc\\hosts'

标签: python windows cmd hosts


【解决方案1】:

首先, 如果您不是管理员,请通过右键单击--> 属性--> 安全 更改主机文件的权限,并允许用户 的读/写/执行权限。 然后以管理员身份打开命令提示符并运行脚本。它会起作用的!

【讨论】:

    【解决方案2】:

    尝试将 python 文件保存为 .pyw 扩展名 这对你有用。

    【讨论】:

      【解决方案3】:

      转到主机文件并取消选中“只读”,然后转到安全选项卡并授予用户读写权限。希望它会工作。

      【讨论】:

        【解决方案4】:

        您应该更改用户对文件的访问权限。 转到 C:\Windows\System32\drivers\etc 并右键单击 properties,选择 security 并编辑对文件的访问权限。

        【讨论】:

          【解决方案5】:

          只需将路径更改为:

          hosts_location = "C:\\Windows\\System32\\drivers\\etc\\hosts"
          

          没有 r",它会工作

          【讨论】:

            猜你喜欢
            • 2014-01-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-23
            • 2022-10-14
            • 2020-07-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多