【软路由】openwrt 断网自动重连拨号

实现原理

定时ping两个外网IP,如果连续N次都ping不通,则用 ifup wan 重启网卡重新拨号

文件及目录

ping检测脚本:/root/ping/ping.sh
守护脚本:/root/ping/daemon.sh 判断ping检测脚本是否有在运行,没有则启动,添加到计划任务定时启动即可
日志:/root/ping/log.txt

ping检测脚本

/root/ping/ping.sh
其中 sshpass -p xxxxx ssh -p 22 root@192.168.2.10 'reboot' 是ssh通知esxi进行软路由重启,xxxxx是密码

#!/bin/sh

#ping 的总次数
PING_SUM=3

#ping 的间隔时间,单位秒
SLEEP_SEC=10

#连续重启网卡 REBOOT_CNT 次网络都没有恢复正常,重启软路由
#时间= (SLEEP_SEC * PING_SUM + 20) * REBOOT_CNT
REBOOT_CNT=30

LOG_PATH="/root/ping/log.txt"

cnt=0
reboot_cnt=0
while :
do
    ping -c 1 -W 1 114.114.114.114 > /dev/null
    ret=$?
    
    ping -c 1 -W 1 223.6.6.6 > /dev/null
    ret2=$?
    
    if [[ $ret -eq 0 || $ret2 -eq 0 ]]
    then
        echo 'Network OK!'
        cnt=0
        reboot_cnt=0
    else
        cnt=`expr $cnt + 1`
        echo -n `date '+%Y-%m-%d %H:%M:%S'` >> $LOG_PATH
        printf '-> [%d/%d] Network maybe disconnected,checking again after %d seconds!\r\n' $cnt $PING_SUM $SLEEP_SEC >> $LOG_PATH
        printf '-> [%d/%d] Network maybe disconnected,checking again after %d seconds!\r\n' $cnt $PING_SUM $SLEEP_SEC 
        
        if [ $cnt == $PING_SUM ]
        then
            echo 'ifup wan!!!' >> $LOG_PATH
            echo 'ifup wan!!!'
            
            ifdown wan
            sleep 1
            ifup wan
            
            cnt=0
            #重连后,等待20秒再进行ping检测
            sleep 20
            
            
            #网卡重启超过指定次数还没恢复正常,重启软路由
            reboot_cnt=`expr $reboot_cnt + 1`
            if [ $reboot_cnt == $REBOOT_CNT ]
            then
                echo -n `date '+%Y-%m-%d %H:%M:%S'` >> $LOG_PATH
                echo '-> =============== reboot!' >> $LOG_PATH
                echo '-> =============== reboot!'
                
                sshpass -p xxxxx ssh -p 22 root@192.168.2.10 'reboot'  
            fi
        fi
    fi
    
    sleep $SLEEP_SEC
done



守护脚本

/root/ping/daemon.sh

#!/bin/sh

LOG_PATH="/root/ping/log.txt"

# 用ps获取ups进程数量
NUM=`ps | grep ping.sh | grep -v grep | wc -l`
echo ${NUM}

# 少于1,重启进程
if [ "${NUM}" -lt "1" ]
then
    /root/ping/ping.sh > /dev/null &
    echo -n `date '+%Y-%m-%d %H:%M:%S'` >> $LOG_PATH
    echo '-> Ping daemon start' >> $LOG_PATH
fi
exit 0


计划任务定时执行守护脚本

编辑文件 /var/spool/cron/crontabs/root 在最后边添加一行

*/1 * * * * /root/ping/daemon.sh

意思为每分钟,执行一次 daemon.sh 脚本

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值