首页 > 解决方案 > 网站拦截器在停止进程后继续阻止网站

问题描述

我编写了一个可以阻止某些网站的网站拦截器。一旦我运行脚本,网站就会被阻止。我面临的问题是,尽管停止了该过程,但我仍然无法访问这些网站。换句话说,我终止程序后网站仍然被阻止。这是我的代码:

import time
import os
os.chdir("C:/Windows/System32/drivers/etc/")
file = open('hosts', 'w')
hosts_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"

website_blocked = ["www.facebook.com", "facebook.com", "www.twitter.com", "twitter.com", "www.instagram.com"
    , "instagram.com"]

while True:
    if 1 == 1:
        print("Working Blocked")
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for website in website_blocked:
                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_blocked):
                    file.write(line)

            file.truncate()

        print("Website Allowed")
    time.sleep(5)

我想知道如何让网站拦截器在进程停止后停止阻止网站。

标签: pythonpython-3.9

解决方案


您可以使用atexit将清理功能添加到您的脚本中,以解除对站点的阻止。

def unblock(hosts_path,website_blocked):
    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_blocked):
                file.write(line)
        file.truncate()
    
import atexit
atexit.register(unblock, hosts_path, website_blocked)

推荐阅读