旁路断网自动切换
Table of Contents
前
因为家里使用旁陆游的方式来进行部署,有时候折腾会导致断网和不稳定的情况,为了让家庭网络可以自断网之后快速恢复。
就想了一个方法,使用脚本在路由上运行进行ping test,出现问题则调用系统配置进行网关切换。
注:此文已经过期,有更优秀的Keepalive方式,链接
正文
部署下面的脚本在 华硕路由器上,定期去检查旁路由是否可用,不可用则使用系统api来进行默认网关变更。
#!/bin/bash
default_gateway='192.168.0.4'
auxiliary_gateway='192.168.0.1'
# Use 8.8.8.8
up_gateway='8.8.8.8'
pkt_num=3
check_ip_available(){
ping -c $pkt_num $1 | grep packets | awk '{print $4}'
}
# If the gateway of the up close, the network is completely unusable
res=`check_ip_available $up_gateway`
echo $res
if [ $((res)) -eq 0 ]; then
echo "up_gateway unusable"
exit 1
fi
cur_gateway=`/bin/nvram get dhcp_gateway_x` # get current gateway
if [ "$cur_gateway" = "$default_gateway" ]; then
echo "cur is default_gateway"
res=`check_ip_available $auxiliary_gateway`
if [ $(($res)) -eq 0 ]; then
echo "auxiliary_gateway not avaliable, abort"
exit 1
fi
res=`check_ip_available $cur_gateway`
if [ $(($res)) -eq $pkt_num ]; then
echo "default_gateway works fine, skip"
exit 1
fi
echo "switch to auxiliary"
# to switch
/bin/nvram set dhcp_gateway_x=$auxiliary_gateway
/bin/nvram set dhcp_dns1_x=$auxiliary_gateway
/bin/nvram set dhcp_dns2_x=""
/bin/nvram commit
/sbin/rc rc_service restart_net_and_phy
exit 0
fi
if [ "$cur_gateway" = "$auxiliary_gateway" ]; then
echo "cur is auxiliary_gateway"
res=`check_ip_available $auxiliary_gateway`
if [ $(($res)) -eq 0 ]; then
echo "auxiliary_gateway not avaliable, abort"
exit 1
fi
res=`check_ip_available $default_gateway`
if [ $(($res)) -eq 0 ]; then
echo "default_gateway still not works, skip"
exit 1
fi
echo "default_gateway works fine now"
echo "switch to default"
# to switch
/bin/nvram set dhcp_gateway_x=$default_gateway
/bin/nvram set dhcp_dns1_x=$default_gateway
/bin/nvram set dhcp_dns2_x=$auxiliary_gateway
/bin/nvram commit
/sbin/rc rc_service restart_net_and_phy
exit 0
fi
echo "nothing change"