效果

image-1681788783792

源码

# -*- encoding: utf-8 -*-
import os.path
import sys
import requests
from pathlib import Path
from loguru import logger
import platform
from shutil import copy2


class Github:
    def __init__(self):
        self.url = "https://raw.hellogithub.com/hosts"
        self.txt = ""
        self.hosts = "/etc/hosts"
        self.tmp = os.path.join(Path.home(), "hosts")
        self.bakTxt = ""
        self.file = self.hosts
        self.windows = False
        if platform.system().lower() == "windows".lower():
            disk = os.getenv("SystemDrive")
            self.file = self.tmp
            self.windows = True
            self.hosts = f"{disk}/WINDOWS/system32/drivers/etc/hosts"
        self.hostsBak = self.hosts + ".bak"
        logger.debug(f"当前系统HOSTS文件路径: {self.hosts}")

    def get(self):
        req = requests.get(url=self.url)
        if req.status_code != 200:
            logger.error(f"请求失败: {self.url}")
            sys.exit(1)
        self.txt = req.content.decode(encoding="utf8")

    def write(self):
        """
        写入配置
        :return:
        """
        txt = self.bakTxt + "\n" + self.txt
        try:
            with open(file=self.file, mode="w", encoding="utf8") as w:
                w.write(txt)
                w.close()
            logger.info("写入配置成功")
        except Exception as e:
            print(txt)
            logger.error(str(e))
            logger.error(f"写入文件失败: {self.file}")
            sys.exit(4)
        if self.windows:
            try:
                copy2(src=self.file, dst=self.hosts)
            except Exception as e:
                logger.error(f"覆盖原文件失败,请使用管理员身份运行: {str(e)}")
                sys.exit(5)

    def dns(self):
        """
        刷新DNS缓存
        :return:
        """
        cmd = "nscd restart"
        if self.windows:
            cmd = "ipconfig /flushdns"
            if os.system(cmd) == 0:
                logger.info("DNS缓存清理成功")
            else:
                logger.error("DNS缓存清理失败,请检查执行权限或者直接重启设备")
        else:
            if os.system("which nscd") == 0:
                if os.system(cmd) == 0:
                    logger.info("DNS缓存清理成功")
                else:
                    logger.error("DNS缓存清理失败,请检查执行权限或者直接重启设备")
            else:
                logger.warning("未安装 nscd 工具,无法手动刷新DNS缓存, 如未生效建议重启设备后使用")
                logger.info("配置结束!")

    def bak(self):
        """
        检查&备份原文件
        :return:
        """
        if not os.path.isfile(self.hostsBak):
            logger.debug("检测到未备份文件,正在进行备份...")
            try:
                copy2(self.hosts, self.hostsBak)
                logger.info("原文件备份成功")
            except Exception as e:
                logger.error(str(e))
        try:
            with open(file=self.hostsBak, mode='r', encoding="utf8") as r:
                self.bakTxt = r.read()
        except Exception as e:
            logger.error(str(e))
            logger.error("无法读取配置文件...")
            sys.exit(5)

    def start(self):
        self.bak()
        self.get()
        self.write()
        self.dns()


if __name__ == "__main__":
    g = Github()
    g.start()