无法使用python编辑主机文件 [英] Unable to edit hosts file with python

查看:73
本文介绍了无法使用python编辑主机文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个Python脚本,该脚本可以根据一天中的时间阻止网站,但是即使以管理员身份运行cmd,我也无法在Windows中编辑主机文件.这是代码:

I am trying to write a python script which can block websites based on the time of the day but i am not able to edit the hosts file in windows even running the cmd as an administrator. Here's the Code:

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]:权限被拒绝".另外,即使作为管理员,我也无法使用记事本编辑主机,因为我的操作系统是64位Windows 10家庭版.

Update:The code is working fine for a local hosts file but when i try it for the real hosts file even as administrator the script just flashes and with cmd shows message "[Errno 13]:Permission Denied". Also i am not able to edit hosts even with notepad even as adminstrator my os is windows 10 home edition 64-bit.

推荐答案

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

First of all, If you are not an administrator, change permissions of the hosts file by right clicking--> Properties --> Security and allow Read/Write/Execute Permissions for Users. Then open Command Prompt as administrator and run the script. It will work!

这篇关于无法使用python编辑主机文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆