修改host地址用于访问github

由于墙的原因,访问github经常卡或者打不开,然后根据其他前辈的意见通过python修改host地址实现(由于是初学python,有不对的地方希望大家斧正)

import requests  as rq

import re

from pyquery import PyQuery as pq

def GetNewHostIp():

    try:

        writeHost = []

        githubName = "github.com"

        githubUrl = "https://sites.ipaddress.com/github.com/"

        response = rq.get(githubUrl).text

        doc=pq(response)

        ip_str = doc("#tabpanel-dns-a").text()

        ipList = re.findall(r'[0-9]+(?:\.[0-9]+){3}',ip_str)

        if len(ipList)>0:

            writeHost.append({'DomainName':githubName,'ip':ipList[0]})

            print("\r当前进度: {}%: ".format(30), " " * (30 // 2), end='github.com的ip:' + ipList[0])

        else:

            print("未找到github.com地址")

            exit()

        iptoolUrl = "https://ip.tool.chinaz.com/{url}"

        fastlyName = "github.global.ssl.fastly.net"

        response = rq.post(iptoolUrl.format(url=fastlyName)).text

        doc = pq(response)

        test = doc('.Whwtdhalf.w15-0.lh45')

        if len(test)>0:

            writeHost.append({'DomainName':test[0].text,'ip':test[1].text})

            print("\r当前进度: {}%: ".format(70), " " * (70 // 2), end='github.global.ssl.fastly.net的ip:' + test[1].text)

        else:

            print("未找到fastly地址")

            exit()

       

        assetsName = "assets-cdn.github.com"

        response = rq.post(iptoolUrl.format(url = assetsName)).text

        doc = pq(response)

        test = doc('.WhwtdWrap.bor-b1s.col-gray03').items()

        i = 5

        for item in test:

            i += 5

            writeHost.append({'DomainName':item('.Whwtdhalf.w15-0.lh45')[0].text,'ip':item('.Whwtdhalf.w15-0.lh45')[1].text})

            print('\r当前进度: {}%:'.format(70+i), " " * (70+i // 2), end= 'assets-cdn的ip:'+ item('.Whwtdhalf.w15-0.lh45')[1].text)

        print("\r当前进度: {}%: ".format(100), " " * (100// 2))

    except Exception as e:

        print("出现错误:" + e)

        exit()

    else:

        print("完成ip的获取!")

        return writeHost

print('*'*50)

print("*"*20 + " add by dubo" + "*"*20)

print(" 用于插入更新host文件中github的host地址")

print("*"*50)

#一开始就获取最新ip地址

ipaddressList = GetNewHostIp()

hostUrl = input("默认文件地址为:C:\Windows\System32\drivers\etc\hosts\n请输入host文件地址:")

if hostUrl == "":

    print("地址未输入,将使用默认的地址!")

    hostUrl = "C:\Windows\System32\drivers\etc\hosts"

print("读取host文件内容")

rfile = open(hostUrl,mode='r',encoding='UTF-8')

hostcontent = rfile.read()

print(hostcontent)

if "#Github" not in hostcontent:

    #文件末尾添加

    with open(hostUrl,mode='a',encoding='UTF-8') as f:

        f.write("#Github\n")

        for item in ipaddressList:

            strName = item["DomainName"]

            strip = item["ip"]

            f.write(strip + " "*10 + strName + "\n")

        f.write("#Github")

else:

    lines = []

    with open(hostUrl,mode='r',encoding='UTF-8') as frd:

       startline = -1

       endline = -1

       rows = frd.readlines()

       for i, line in enumerate(rows):

           if "#Github" in line:

               if startline == -1:

                   startline = i

                   lines.append(line)

               else:

                   for item in ipaddressList:

                       strName = item["DomainName"]

                       strip = item["ip"]

                       lines.append(strip + " "*10 + strName + "\n")

                   endline = i

                   lines.append(line)

           elif startline != -1 and endline == -1:

                 pass

           else:

               lines.append(line)

       frd.close()

    with open(hostUrl,mode='w',encoding='UTF-8') as f:

        f.writelines(lines)

                 

       

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值