注意事项
使用管理员权限运行脚本
mac 使用sudo + 拖拽脚本,进行执行
基础版
#!/bin/bash
#获取github.com最新的ip地址
fast_ip=`curl https://github.com.ipaddress.com/|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
echo "github.com最新的ip地址: $fast_ip";
#添加或替换 $fast_ip 到 /etc/hosts 中
if grep "www.github.com" /etc/hosts;then
echo "github dns exists, replace it with the latest one $fast_ip";
sed -i -e "s|[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\} *www\.github\.com|$fast_ip www\.github\.com|" /etc/hosts;
else
echo "github dns does not exist, replace it with the latest one $fast_ip";
echo -e "\n#Github\n$fast_ip www.github.com\n" >> /etc/hosts;
fi
#刷新DNS
dscacheutil -flushcache;
killall -HUP mDNSResponder;
say DNS cache has been flushed;
升级版本
较基础版新增了其他几个网址
注意:本脚本会删除/etc/hosts中的12行到最后一行,如果你的/etc/hosts文件的github内容不是从12行开始,请自主修改一下
#!/bin/bash
# 请使用管理员模式运行此文件
github_com=`curl https://github.com.ipaddress.com/|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
gist_github_com=`curl https://github.com.ipaddress.com/gist.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
help_github_com=`curl https://github.com.ipaddress.com/help.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
nodeload_github_com=`curl https://github.com.ipaddress.com/nodeload.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
raw_github_com=`curl https://github.com.ipaddress.com/raw.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
status_github_com=`curl https://github.com.ipaddress.com/status.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
training_github_com=`curl https://github.com.ipaddress.com/training.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
assets_cdn_github_com=`curl https://github.com.ipaddress.com/assets-cdn.github.com|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
github_global_ssl_fastly_net=`curl https://fastly.net.ipaddress.com/github.global.ssl.fastly.net|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n '2p'`;
ip_arr=($github_com $gist_github_com $help_github_com $nodeload_github_com $raw_github_com $status_github_com $training_github_com $assets_cdn_github_com $github_global_ssl_fastly_net)
addr_arr=("github.com" "gist.github.com" "help.github.com" "nodeload.github.com" "raw.github.com" "status.github.com" "training.github.com" "assets-cdn.github.com" "github.global.ssl.fastly.net")
# 如果已经有了 github.com,则先删除
if grep "github.com" /etc/hosts;then
echo "删除12行到最后一行";
sed -i '' '12,$d' /etc/hosts;
fi
# 拼接 str
str=""
for ((i=0; i<${#ip_arr[*]}; i++))
do
str="$str\n${ip_arr[i]} ${addr_arr[i]}"
done
echo -e ${str}
# 将 str 写入文件
echo -e "$str" >> /etc/hosts;
# 刷新DNS
dscacheutil -flushcache;
killall -HUP mDNSResponder;
say DNS cache has been flushed;
结语
就我个人而言,设置了/etc/hosts,仍然解决不了我访问github慢的问题,但还是将我写出的脚本发上来,万一有人就有用了