如何一次性解决 github 无法访问问题?

377 阅读2分钟

前言

自己为了高速稳定访问 github 尝试过很多方法,最近使用的方法是 switchhosts 定时更新 github ip 地址的方式,但最近也不稳定,在 git push 和 git pull 时一直卡住,非常影响使用体验(已经开了魔法也是一样);

遂请教 mentor 他的方法,他给我推荐了定时查询 github 高速访问地址的方式,测试结果:

image.png

速度如上:相比于之前的 170kb/s,我已经知足了。

配置过程

主要用到两个命令

  • 查询高速访问地址:nslookup github.global.ssl.fastly.Net
  • 查询 github ipv4 地址:nslookup github.com

image.png

输出格式如上,我们只需要最后的那个裸 ip 地址,所以使用 grep 和 sed 过滤一下即可

touch ~/github.sh
vi ~/github.sh

将下面的脚本拷贝到脚本文件中

#!/bin/bash 

ip1=$(nslookup github.global.ssl.fastly.Net | grep '^Address:' | grep -v "#" | sed 's/Address: //') 

ip2=$(nslookup github.com | grep '^Address:' | grep -v "#" | sed 's/Address: //') 

echo "github.global.ssl.fastly.Net $ip1" > /etc/hosts # 覆盖 

echo "github.com $ip2" >> /etc/hosts # 追加

添加执行权限(在执行之前最好备份一下你的 /etc/hosts 文件(如果你之前里面有内容的话))

sudo cp /etc/hosts /etc/hosts.swp
sudo chmod +x ~/github.sh
sudo chmod 777 /etc/hosts
./github.sh
cat /etc/hosts

image.png

到这里就相当于配置好了 github 高速访问地址,那如果我们电脑可以每个小时去获取一下这个高速访问地址,我们就无需手动操作了。

定时任务

在macOS上使用launchd来启动后台定时执行任务需要创建一个plist(属性列表)文件,该文件定义了任务的具体内容和调度时间。launchd是macOS的服务管理框架,用于启动、停止和管理守护进程、应用程序代理、定时任务等。

直接给出过程

cd /Library/LaunchDaemons 

sudo vim com.example.github.plist 

复制下面 plist 内容到 com.example.github.plist 中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
    <dict> 
        <key>Label</key> 
        <string>com.example.github</string> 
        <key>ProgramArguments</key> 
        <array> 
            <string>/bin/bash</string>
            <string>/Library/LaunchDaemons/github.sh</string> 
        </array>
            <key>StartInterval</key> 
            <integer>3600</integer> 
    </dict> 
</plist>

启动系统级后台定时任务并查看是否启动成功

sudo mv ~/github.sh /Library/LaunchDaemons/
sudo chmod 644 com.example.github.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.example.github.plist 
sudo launchctl list | grep com.example.github

image.png

over