import datetime
import os

# 设置屏蔽的网站列表
blocked_sites = ["www.kugou.com", "y.qq.com", "music.163.com", "www.bilibili.com"]

# 获取当前时间
now = datetime.datetime.now()

# 设置屏蔽时间段为每天中午1:40至2:00
start_time = now.replace(hour=13, minute=40, second=0, microsecond=0)
end_time = now.replace(hour=14, minute=0, second=0, microsecond=0)

# 判断当前时间是否在屏蔽时间段内
if start_time <= now <= end_time:
    # 打开hosts文件
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as file:
        # 读取hosts文件内容
        content = file.read()
        for site in blocked_sites:
            # 在hosts文件中添加屏蔽规则
            if site not in content:
                file.write("127.0.0.1 {}\n".format(site))
else:
    # 如果不在屏蔽时间段内，移除hosts文件中的屏蔽规则
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as file:
        content = file.readlines()
        # 将不需要屏蔽的行写回文件
        file.seek(0)
        for line in content:
            if not any(site in line for site in blocked_sites):
                file.write(line)
        # 截断文件，删除多余的内容
        file.truncate()

# 刷新DNS缓存
os.system("ipconfig /flushdns")
