import os
import tkinter as tk

# 确认密码的函数
def check_password():
    # 获取输入的密码
    password = password_entry.get()
    # 如果密码正确，解锁网站并关闭窗口
    if password == "unlockhosts":
        unblock_sites()
        window.destroy()
    # 如果密码错误，清空并重新获取输入框焦点
    else:
        password_entry.delete(0, tk.END)
        password_entry.focus()

# 解锁网站的函数
def unblock_sites():
    # 要解锁的网站列表
    unblocked_sites = ["www.kugou.com", "y.qq.com", "music.163.com", "www.bilibili.com"]
    # 打开hosts文件
    with open(r"C:\Windows\System32\drivers\etc\hosts", "r+") as file:
        # 读取hosts文件内容
        content = file.readlines()
        # 将需要解锁的行从hosts文件中删除
        file.seek(0)
        for line in content:
            if not any(site in line for site in unblocked_sites):
                file.write(line)
        # 截断文件，删除多余的内容
        file.truncate()

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

# 创建主窗口
window = tk.Tk()
window.title("Unlock Hosts")
# 设置窗口大小和位置（居中显示）
window_width, window_height = 300, 100
screen_width, screen_height = window.winfo_screenwidth(), window.winfo_screenheight()
x, y = (screen_width - window_width) // 2, (screen_height - window_height) // 2
window.geometry("{}x{}+{}+{}".format(window_width, window_height, x, y))

# 创建Label和Entry组件
password_label = tk.Label(window, text="Password Required：")
password_label.pack(side=tk.TOP, pady=5)
password_entry = tk.Entry(window, show="*")
password_entry.pack(side=tk.TOP, padx=10, pady=5)
password_entry.focus()

# 创建确认按钮
confirm_button = tk.Button(window, text="Enter", command=check_password)
confirm_button.pack(side=tk.BOTTOM, pady=5)

# 进入主循环
window.mainloop()
