欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

update_hosts 自己亲自做的 更新 添加 三条记录到 hosts python 脚本 有大用 有大大用

import os
import ctypes
import tkinter as tk
from tkinter import messagebox


def add_hosts_entries():
    # 定义要添加的hosts条目
    new_entries = [
        "192.168.0.1 aaa.com",
        "192.168.0.2 bbb.com",
        "192.168.0.2 ccc.com"
    ]

    # 获取hosts文件路径
    hosts_path = r"C:\Windows\System32\drivers\etc\hosts"

    try:
        # 检查管理员权限
        if not ctypes.windll.shell32.IsUserAnAdmin():
            messagebox.showerror("权限错误", "请以管理员身份运行此程序")
            return 0

        # 检查条目是否已存在
        existing_entries = set()
        if os.path.exists(hosts_path):
            with open(hosts_path, 'r') as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#'):
                        existing_entries.add(line.split('#')[0].strip())

        # 添加新条目(跳过已存在的)
        added = -1
        with open(hosts_path, 'a') as f:
            for entry in new_entries:
                if entry not in existing_entries:
                    f.write("\n" + entry)
                    added = 1

        return added

    except Exception as e:
        messagebox.showerror("错误", f"操作失败: {str(e)}")
        return False


if __name__ == "__main__":
    # 隐藏主Tkinter窗口
    root = tk.Tk()
    root.withdraw()

    # 执行添加操作
    result = add_hosts_entries()

    # 显示结果弹窗
    if result == 1:
        messagebox.showinfo("完成", "hosts文件更新成功!")
    elif result == 0:
        messagebox.showinfo("完成", "未更改hosts文件(无权限)!")
    elif result == -1:
        messagebox.showinfo("完成", "未修改hosts文件(条目已存在)")
    # 其他错误情况已在函数内处理


普通分类: