【python】自动更换本地HOSTS中github.com的ip指向为最低延迟ip

2021/10/4 14:40:43

本文主要是介绍【python】自动更换本地HOSTS中github.com的ip指向为最低延迟ip,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

也不知道是从什么时候开始,国内网络访问github动不动就抽风,几分钟快几分钟断,实在受不了了,网上找到了一个chrome插件,但是那ip更新频率也太低了,经常用不了
所以就自己用python写了个自动找最快ip并且自动修改本地hosts的程序

https://github.com/Dark-Athena/auto-github-hosts-py

#!/usr/bin/env python
#coding=utf-8
#功能 :自动设置github.com的host ip
#日期 :2021-09-25 
#作者:Dark-Athena
#email :darkathena@qq.com
#说明:自动从备选ip清单中寻找最低延时IP,设置到本地host中,需要使用管理员权限运行
"""
Copyright DarkAthena
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""
import ping3

iplist=list((
"13.250.177.223",
"52.69.186.44",
"140.82.112.4",
"52.74.223.119",
"15.164.81.167",
"140.82.113.3",
"13.229.188.59",
"140.82.112.3",
"140.82.114.3",
"20.205.243.166",
"52.192.72.89",
"140.82.121.3",
"140.82.113.4",
"52.78.231.108",
"13.114.40.48",
"140.82.114.4",
"140.82.121.4"
))
PingTime=0.0
MinTime=999.0
for k in iplist:
    PingTime=ping3.ping(k,timeout=1,unit='ms')
    if not PingTime:
        PingTime=5000.0
    if PingTime<MinTime:
        MinTime=PingTime
        FastIp=k
    print(k+','+str(int(PingTime)))
print('最快IP是:'+FastIp+' 延迟'+str(int(MinTime))+'ms')

HOST = r'C:\Windows\System32\drivers\etc\HOSTS'
new_data=''

try:
     with open(HOST, 'r+', encoding='utf-8') as f:
        data = f.readlines()
        if (data[-1][-1:2])!='\n':
            data[-1]=data[-1]+'\n'
        for line in data:
            if (' github.com\n' in line or ' github.com ' in line ) and '#' not in line:
                line=(FastIp+' github.com\n')
            new_data+=line
        f.close()
     with open(HOST,"w+",encoding="utf-8") as f:
        f.write(new_data)
        f.close()
        print('修改成功')
except Exception as e:
    print(e)

这些备选ip是从站长之家查出来的所有能通的海外ip,之后会尝试修改成自动更新这个ip列表



这篇关于【python】自动更换本地HOSTS中github.com的ip指向为最低延迟ip的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程