ledge openwrt上自动检测网络并重启

date
Jun 10, 2022
slug
tip-openwrt-auto-check-network-and-reboot
status
Published
summary
小技巧
tags
tip
type
Post
URL

Problem & Summary

Solution

核心就是 ifdown WAN;sleep 1;ifup WAN

vi /root/network-watch-dog.sh

#!/bin/sh
# filename: /root/network-watch-dog.sh
# 4=network error/refused/timeout/dns err/
# need "opkg install wget ca-bundle"

count=0
URLs='http://baidu.com  http://163.com  http://www.qq.com'
for host in $URLs ; do
    #echo $host
    # wget -t2 这个参数要>=2, 防止第一次访问dns解析超时,而导致失败
    wget -q -T2 -t2 --method=HEAD --max-redirect=0 "$host"
    if [ 4 -eq $? ]; then
        echo $(date +%F_%T%z) $host 'error.' >> /root/log.redail
        count=$((count+1))
    else
        break
    fi
done
URL_cnt=$(echo $URLs|wc -w)
if [ $count -ge $URL_cnt ]; then
    echo $(date +%F_%T%z) redail >> /root/log.redail
    ifdown WAN;sleep 1;ifup WAN
fi

另外一个working script

#!/bin/sh
# filename: /root/network-watch-dog.sh

# 这里直接固定 ping ali dns
SUCCESS_COUNT=$(ping 223.5.5.5 -c ${PING_COUNT} 2>&1 | grep '64 bytes' | wc -l)

if [ ${SUCCESS_COUNT} == 0 ]; then
  TIMESTAMP=$(date +%s)

  if [ -f ${LOCK_FILE_PATH} ]; then
    LOCK_TIMESTAMP=$(cat ${LOCK_FILE_PATH})
    # 超过最大等待时间 删除锁文件重启
    if [ $(expr ${TIMESTAMP} - ${LOCK_TIMESTAMP}) -ge ${MAX_WAITING_SECONDS} ]; then
      rm -rf ${LOCK_FILE_PATH}
      reboot
    fi
  else
    # 写入断网时间到锁文件
    echo ${TIMESTAMP} > ${LOCK_FILE_PATH}
  fi
  ifdown WAN;sleep 1;ifup WAN
else
  # 成功联网后判断上次断网遗留的锁文件
  if [ -f ${LOCK_FILE_PATH} ]; then
    rm -rf ${LOCK_FILE_PATH}
  fi
fi
notion image
notion image
notion image

touch /root/network-watch-dog.log

crontab -e

root@Lede7200_104:~# crontab -l
*/3 * * * * /bin/sh /root/network-watch-dog.sh

Screenshots

 

© Ying Bun 2021 - 2024