Loading... 为了方便远程连接实验室里的台式机写了个脚本 脚本功能: * 检测是否连接公网,若断开则重新登录 * 检测是否连接内网,若断开则重启`WAN`接口或者重启路由器 * ~~重新连接公网后,进行`DDNS`~~ ```shell 2-59/2 * * * * flock -xn /tmp/run.lock -c '/bin/ash /root/watchdog.sh username password' ``` 偶数分钟运行脚本, 使用`flock`防止任务重复运行 `/root/watchdog.sh` 如下: ```shell #!/bin/bash DATE=$(date +%Y-%m-%d-%H:%M:%S) LOG_FILE="/root/log.txt" MAX_RETRIES=5 PING_ADDRESS="223.5.5.5" PING_FAILBACK="119.29.29.29" RELOGIN_URL="http://10.9.1.3:801/eportal/" echo "$DATE" > "$LOG_FILE" echo "watchdog start" >> "$LOG_FILE" # Ping check function ping_check() { local address=$1 /bin/ping -c 1 $address >/dev/null return $? } # WAN Interface Restart restart_wan() { echo "Restarting WAN interface..." >> "$LOG_FILE" ifdown wan6 sleep 5 ifdown wan sleep 5 ifup wan sleep 5 ifup wan6 sleep 5 } # Retry ping function with exponential backoff retry_ping() { local address=$1 local retries=$2 local interval=1 for i in $(seq 0 $((retries - 1))); do if ping_check $address; then echo "Ping to $address successful, exiting..." >> "$LOG_FILE" return 0 fi echo "Ping attempt $((i+1)) failed, retrying in $interval seconds..." >> "$LOG_FILE" sleep $interval interval=$((interval * 2)) # Exponential backoff done return 1 } # Function to obtain WAN IP get_wan_ip() { ip=$(ifstatus wan | jsonfilter -e '@["ipv4-address"][0].address') echo "$ip" } # Relogin function relogin() { local ip=$1 local user_account=$2 local user_password=$3 response=$(curl --connect-timeout 5 "$RELOGIN_URL?c=Portal&a=login&callback=dr1003&login_method=1&user_account=%2C0%2C$user_account&user_password=$user_password&wlan_user_ip=$ip&wlan_user_ipv6=&wlan_user_mac=000000000000&wlan_ac_ip=&wlan_ac_name=&jsVersion=3.3.3&v=6438") if [[ "$response" == *"\"result\":\"1\""* ]]; then echo "Relogin success with IP: $ip" >> "$LOG_FILE" return 0 else echo "Relogin failed" >> "$LOG_FILE" return 1 fi } # Main logic if retry_ping $PING_ADDRESS $MAX_RETRIES; then exit 0 fi echo "Network offline, attempting relogin..." >> "$LOG_FILE" ip=$(get_wan_ip) if [[ -z "$ip" ]]; then echo "Failed to retrieve WAN IP, restarting WAN interface" >> "$LOG_FILE" restart_wan ip=$(get_wan_ip) fi if [[ -n "$ip" ]]; then echo "Current WAN IP: $ip" >> "$LOG_FILE" if relogin $ip $1 $2; then echo "Successfully relogged in, exiting..." >> "$LOG_FILE" exit 0 else echo "Relogin failed, continuing with recovery steps" >> "$LOG_FILE" fi else echo "WAN IP still unavailable after restart, rebooting system" >> "$LOG_FILE" reboot fi # If relogin fails, attempt to retry ping as a final check before reboot if ! retry_ping $PING_FAILBACK $MAX_RETRIES; then echo "Still offline after relogin attempt, rebooting system" >> "$LOG_FILE" reboot else echo "Network restored after relogin" >> "$LOG_FILE" fi ``` 最后修改:2024 年 10 月 11 日 08 : 23 PM © 允许规范转载 赞赏 如果觉得我的文章对你有用,请随意赞赏 赞赏作者 支付宝微信
2 条评论
《小镇春色》欧美剧高清在线免费观看:https://www.jgz518.com/xingkong/33599.html
《泪痕剑》国产剧高清在线免费观看:https://www.jgz518.com/xingkong/39363.html