Python写的小脚本附源码,通过更新修改host里DNS来优化github的打开下载速度。

使用方法:
运行后,闪一下就过去了,host已经修改完看上图,再次打开github就可以了。
python源码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import urllib.request
import re
import subprocess
# 配置
HOSTS_URL = "https://raw.hellogithub.com/hosts"
LOCAL_HOSTS_PATH = {
"nt": r"C:\Windows\System32\drivers\etc\hosts",
"posix": "/etc/hosts"
}.get(os.name, "/etc/hosts")
GITHUB_HOSTS_MARK = "# GitHub520 Host Start"
END_MARK = "# GitHub520 Host End"
def fetch_latest_hosts():
try:
print("🌐 正在从 HelloGitHub 获取最新的 GitHub hosts...")
with urllib.request.urlopen(HOSTS_URL, timeout=15) as resp:
content = resp.read().decode('utf-8')
return content
except Exception as e:
print(f"❌ 获取 hosts 失败: {e}")
return None
def read_current_hosts():
try:
with open(LOCAL_HOSTS_PATH, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
print(f"❌ 无法读取 hosts 文件: {e}")
return None
def flush_dns_cache():
"""跨平台刷新 DNS 缓存"""
print("🔄 正在刷新 DNS 缓存...")
try:
if os.name == 'nt': # Windows
subprocess.run(["ipconfig", "/flushdns"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
elif sys.platform.startswith('darwin'): # macOS
# macOS Monterey (12.0+) 及更高版本使用 'dscacheutil' 和 'sudo killall -HUP mDNSResponder'
subprocess.run(["sudo", "dscacheutil", "-flushcache"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["sudo", "killall", "-HUP", "mDNSResponder"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else: # Linux
# 尝试多种可能的服务
services = ["systemd-resolved", "nscd", "dnsmasq", "NetworkManager"]
flushed = False
for svc in services:
try:
if svc == "systemd-resolved":
subprocess.run(["sudo", "resolvectl", "flush-caches"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
elif svc == "nscd":
subprocess.run(["sudo", "systemctl", "restart", "nscd"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
continue
flushed = True
break
except (subprocess.CalledProcessError, FileNotFoundError):
continue
if not flushed:
# 通用提示
print("ℹ️ 未检测到已知 DNS 服务,Linux 用户可手动运行 'sudo systemd-resolve --flush-caches'(如适用)")
print("✅ DNS 缓存已刷新!")
except Exception as e:
print(f"⚠️ 刷新 DNS 缓存时出错(可忽略): {e}")
def write_hosts(new_content):
try:
with open(LOCAL_HOSTS_PATH, 'w', encoding='utf-8') as f:
f.write(new_content)
print("✅ hosts 文件已更新!")
flush_dns_cache() # 自动刷新 DNS
except PermissionError:
print("❌ 权限不足!请以管理员(Windows)或 root(macOS/Linux)身份运行此脚本。")
sys.exit(1)
except Exception as e:
print(f"❌ 写入 hosts 失败: {e}")
sys.exit(1)
def is_admin():
"""跨平台判断是否具有管理员/root 权限"""
if os.name == 'nt':
try:
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
else:
return os.geteuid() == 0
def main():
print("🚀 GitHub 访问加速工具(自动更新 hosts + 刷新 DNS)")
if not is_admin():
if os.name == 'nt':
print("🛑 错误:请右键选择“以管理员身份运行”此脚本。")
else:
print("🛑 错误:请使用 'sudo python3 github_hosts_accelerator.py' 运行。")
sys.exit(1)
new_hosts = fetch_latest_hosts()
if not new_hosts:
sys.exit(1)
current_hosts = read_current_hosts()
if current_hosts is None:
sys.exit(1)
# 移除旧的 GitHub520 区块(如果存在)
pattern = re.compile(re.escape(GITHUB_HOSTS_MARK) + r".*?" + re.escape(END_MARK), re.DOTALL)
cleaned_hosts = pattern.sub("", current_hosts).strip()
# 确保末尾有换行
final_hosts = cleaned_hosts + "\n\n" + new_hosts.strip() + "\n"
write_hosts(final_hosts)
print("\n🎉 操作完成!现在可以尝试访问 GitHub 或执行 git clone 了。")
print("\n按任意键退出")
if __name__ == "__main__":
main()工具参数:
| 工具名称: | GitHub加速器1.0 |
| 运行系统: | windows |
| 文件格式: | exe |
| 文件大小: | 6M |
| 工具截图: | 有 |

































发表评论
膜拜大神