ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-10-04 14:33:21  阅读:232  来源: 互联网

标签:github 140.82 License python ip PingTime com


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

标签:github,140.82,License,python,ip,PingTime,com
来源: https://blog.csdn.net/wwwwwwgame/article/details/120600125

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有