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

为解决国内访问GitHub频繁不稳定的问题,作者编写了一个Python程序,从预设的IP列表中寻找延迟最低的IP,并自动将其写入本地hosts文件,以优化访问速度。程序需要管理员权限运行,并计划实现IP列表的自动更新。
摘要由CSDN通过智能技术生成

也不知道是从什么时候开始,国内网络访问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列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DarkAthena

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值