python 使用python的网站拦截器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用python的网站拦截器相关的知识,希望对你有一定的参考价值。

import time
from datetime import datetime as dt

start_time = 8
end_time =18

def calculate_sleep_time():
    if dt(dt.now().year, dt.now().month, dt.now().day, start_time) >= dt.now():
        print("if block")
        diff = dt(dt.now().year, dt.now().month, dt.now().day, start_time)-dt.now()
    else:
        print("else block")
        diff = dt(dt.now().year, dt.now().month, dt.now().day, end_time) - dt.now()

    print("utility will sleep for %d seconds" % diff.total_seconds())
    return diff.total_seconds()
        
tmep_host = r'hosts'
hosts = r'/etc/hosts'
redirect = '127.0.0.1'
websites = ['www.facebook.com','facebook.com'] # list of website to block


while True:
    if (dt(dt.now().year, dt.now().month, dt.now().day, start_time) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, end_time)):
        print("Working Hours")
        with open(tmep_host,'r+') as file:
            content = file.read()
            for link in websites:
                if link in content:
                    pass
                else:
                    file.write(redirect + " " + link + "\n")
                    pass
            pass
    else:
        print("Fun time")
        with open(tmep_host,'r+') as file:
            content =  file.readlines()
            file.seek(0)
            for line in content:
                if not any(website in line for website in websites):
                    file.write(line)
            file.truncate()

    time.sleep(calculate_sleep_time())
    pass

以上是关于python 使用python的网站拦截器的主要内容,如果未能解决你的问题,请参考以下文章

Python网络编程7-对Telnet流量进行解码分析与拦截

[转]使用 mitmproxy + python 做拦截代理

Python中常用内建属性:__getattribute__属性拦截器使用详解

15《Python 原生爬虫教程》爬虫和反爬虫

Python Scrapy框架

拦截 Python 中的所有日志记录