为什么即使以管理员身份运行脚本也无法正常工作?

时间:2019-02-11 21:27:01

标签: python windows access-denied

我正在尝试编写一个阻止网站的Python脚本。它应该修改hosts文件,但是,即使以管理员身份运行该命令,它也会拒绝访问。

import time
from datetime import datetime as dt

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

while True:
    if dt(dt.now().year,
          dt.now().month,
          dt.now().day, 1) < dt.now() < dt(dt.now().year,
                                           dt.now().month,
                                           dt.now().day, 16):
        print("working time")
        with open(hosts_path, '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_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)
            file.truncate()
        print("fun hours")
    time.sleep(5)

我该如何解决?

0 个答案:

没有答案