自动更新host实现github加速
如题,当前github的dns已经被污染,在不同cdn加持下,经常会抽风,虽然已经被微软收购,目前的整治可能还需一段时间,目前主流的优化方法无非也就几种,考虑安全风险问题,所以不推荐使用镜像加速,当然修改dns也有安全隐患,这个仁者见仁智者见智吧,分享一个自动修改host实现github加速的脚本。
原理简介
- 首先查询github在当前网路最佳的访问节点(存在安全隐患,如果不信任站长工具给的IP可以换成其他源,只要给的节点能够有效加速)
- 拷贝IP,打开系统host文件,单机修改时如此,如果在自己的局域网修改,则需要在dns服务器上设置,因为过期时间较短,建议制作成定时任务的形式更新(以下是我目前的host)。
185.199.110.153 assets-cdn.Github.com
#140.82.114.4 github.com
#52.192.72.89 github.com
# ipconfig /flushdns
#20.205.243.166 github.com
199.232.69.194 github.global.ssl.fastly.net
185.199.109.133 raw.githubusercontent.com
13.114.40.48 github.com
#52.69.186.44 github.com
源码
# coding=utf-8
"""
查询访问github最佳的女生路线并配置到电脑host文件中
dns来源:站长工具
"""
import json
import logging
import os
import platform
try:
# noinspection PyCompatibility
from urllib.request import urlopen, Request
# noinspection PyCompatibility
from urllib.error import HTTPError, URLError
except ImportError:
# noinspection PyUnresolvedReferences,PyCompatibility
from urllib2 import urlopen, Request, HTTPError, URLError
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
host_window = r"C:\Windows\System32\drivers\etc\hosts"
host_unix = r"/etc/hosts"
def get_best_ip(host):
"""查询dns github最佳解析路线, 默认是github"""
# noinspection HttpUrlsUsage
api = "http://tool.chinaz.com/AjaxSeo.aspx?t=dns&server=JACYvxRvL1|CnyK9sCL7~g=="
headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }
data = 'host={host}&type=1&total=10&process=6&right=3'.format(host=host)
req = Request(api, data=data.encode(), headers=headers)
try:
res = urlopen(req).read().decode('utf-8')
res_json = json.loads(res[1: -1])
return (res_json.get('list') or [{}])[0].get('result', '')
except (HTTPError, URLError):
logger.exception("网络连接异常")
except json.decoder.JSONDecodeError:
logger.exception("解析错误")
except UnicodeDecodeError:
logger.exception("解码错误")
except Exception as e:
logger.exception("未知错误 {}".format(e))
return ''
def _get_path():
"""获取host路径"""
if platform.system() is "Windows":
return host_window
return host_unix
def read_host():
"""读取host"""
with open(_get_path(), 'r', encoding='utf-8') as f:
return f.read()
def write_host(text):
"""写入host"""
with open(_get_path(), 'w+', encoding='utf-8') as f:
return f.write(text)
def set_host(host='github.com'):
"""设置host文件"""
host_text = read_host()
logger.info('读取host \n{}'.format(host_text))
host_list = [[keyword.strip() for keyword in line.split() if keyword] for line in host_text.split('\n') if
line and len(line.split()) >= 2]
best_ip = get_best_ip(host)
if not best_ip:
logger.warning('查询到ip数据为空')
return
reset = False
for line in host_list:
# 如果是在使用的IP不与最佳ip相同则进行注释
if line[1] == host:
if not line[0].startswith('#'):
line[0] = "#" + line[0]
if line[0] == "#" + best_ip:
line[0] = line[0].strip("#")
reset = True
if not reset:
host_list.append([best_ip, host])
host_text = '\n'.join([' '.join(line) for line in host_list])
logger.info('修改host \n{}'.format(host_text))
write_host(host_text)
if platform.system() == 'Windows':
os.system('ipconfig /flushdns')
logger.info('设置成功, 当前 {} 的解析IP为 {}'.format(host, best_ip))
if __name__ == '__main__':
set_host()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具