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

这里的技术是共享的

You are here

update_hosts 自己亲自做的 更新 添加 五条记录到 hosts python 脚本 事实上考虑到 hosts 文件是 utf-8编码还是gbk编码的问题,所有完美 有大用 有大大用

事实上考虑到 hosts 文件是 utf-8编码还是gbk编码的问题,所有完美   OK 有大用 

#!/usr/bin/python3
import os
import ctypes
import tkinter as tk
from tkinter import messagebox


def add_hosts_entries():
    # 定义要添加的hosts条目
    new_entries = [
        "192.168.0.100 mmmm.aaaa.com",
        "192.168.0.101 nnnn.aaaa.com",
        "192.168.0.102 kkkk.aaaa.com",
        "192.168.0.103 llll.aaaa.com",
        "192.168.0.104 pppp.bbbbb.com"
    ]

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

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

        encoding_used = "utf-8"  # 默认使用UTF-8编码
        # 检查条目是否已存在
        existing_entries = set()
        if os.path.exists(hosts_path):
                try:
                    with open(hosts_path, 'r',encoding='utf-8') as f:
                        for line in f:
                            line = line.strip()
                            if line and not line.startswith('#'):
                                existing_entries.add(line.split('#')[0].strip())
                        encoding_used = "utf-8"
                except UnicodeDecodeError:
                    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())
                        encoding_used = "system_default"

        # 添加新条目(跳过已存在的)
        added = -1

        if encoding_used == "utf-8":
            with open(hosts_path, 'a',encoding='utf-8') as f:
                for entry in new_entries:
                    if entry not in existing_entries:
                        f.write("\n" + entry)
                        added = 1
        else:
            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文件(条目已存在)")
    # 其他错误情况已在函数内处理



普通分类: