无法使用python编辑本地主机文件

时间:2018-11-08 05:59:07

标签: python-3.x hosts

我正在尝试构建一个程序,该程序将在特定的工作时间段内阻止某些网站。我首先在对主机文件(位于C:\ Users \ Alberto \ Documents \ Atom \ web-blocker)上的修改进行测试,然后将其复制到与程序相同的文件中,然后再修改主要的hosts文件。但是,即使我的脚本允许我在上班时间或不在工作时间正确打印出消息,但问题是网站列表未在本地主机文件中打印出来。另外,我以管理员身份运行该程序。

这是我的代码:

import time
from datetime import datetime as dt

hosts_temp="hosts"
hosts_path=r"C:\Windows\System32\drivers\etc\hosts"
redirect="127.0.0.1"
website_list=["www.facebook.com","facebook.com","youtube.com","www.youtube.com"]


while True:
    if dt(dt.now().year,dt.now().month,dt.now().day,6) < dt.now() < 
dt(dt.now().year,dt.now().month,dt.now().day,19):
        print("Working hours, get back to work you future data scientist!")
        with open(hosts_temp,"r+") as file:
            content=file.read()
            for website in website_list:
                if website in content:
                    pass
                else:
                    file.write(redirect+" "+ website +"\n")

    else:
        with open(hosts_temp, '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)
                file.truncate()
         print("Fun hours...")
    time.sleep(5)

要修改本地主机文件,我缺少什么?预先感谢您的帮助。

0 个答案:

没有答案