shell 检测主机10分钟不能联网就关机

2024/12/09

crontab

*/3 * * * * /path/to/network_watchdog.sh >> /var/log/network_watchdog_cron.log 2>&1
#!/bin/bash

# 配置项
TARGET_IP="8.8.8.8"    # 目标IP地址或域名,默认为Google的公共DNS服务器
TIMEOUT=600              # 超时时间(秒),10分钟=600秒
LOG_FILE="/var/log/network_watchdog.log"

# 记录开始时间(使用文件存储)
start_time_file="/tmp/network_watchdog_start_time"

# 检查是否可以联网
function check_network() {
    if ping -c 1 -W 5 $TARGET_IP > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# 初始化或读取开始时间
if [ ! -f "$start_time_file" ]; then
    echo $(date +%s) > "$start_time_file"
fi

start_time=$(cat "$start_time_file")

# 检查网络连接状态
if check_network; then
    echo "$(date) - 网络正常" >> $LOG_FILE
    echo $(date +%s) > "$start_time_file"  # 重置计时器
else
    current_time=$(date +%s)
    elapsed_time=$((current_time - start_time))
    
    if [ $elapsed_time -ge $TIMEOUT ]; then
        echo "$(date) - 网络中断超过$((TIMEOUT / 60))分钟,正在关机..." >> $LOG_FILE
        sudo shutdown -h now
        exit 1
    else
        echo "$(date) - 网络不可达,已持续$((elapsed_time / 60))分钟" >> $LOG_FILE
    fi
fi

目录