• 已删除用户
陈永强
陈永强
发布于 2026-06-29 / 3 阅读
0

Ubuntu ping 不通IP自动关机

Ubuntu ping 不通IP自动关机

ping 监控脚本 ping_monitor_loop.sh

#!/bin/bash

TARGET_IP="114.114.114.114" # 需要ping的ip
FAIL_COUNT=0 #记录失败次数
MAX_FAILURES=3 #ping 失败的最大次数
CHECK_INTERVAL=120  # ping的间隔时间 单位: 秒
LOG_FILE="/usr/local/ping_monitor/monitor.log" #日志记录位置 和脚本在同一目录下

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

log_message "Ping监控服务已启动,目标: $TARGET_IP"

while true; do
	log_message "Ping执行,目标: $TARGET_IP"
    log_message "Ping $TARGET_IP "
    if ping -c 1 -W 2 "$TARGET_IP" > /dev/null 2>&1; then
        if [ "$FAIL_COUNT" -ne 0 ]; then
            log_message "Ping成功,重置失败计数器"
            FAIL_COUNT=0
        fi
    else
        FAIL_COUNT=$((FAIL_COUNT + 1))
        log_message "Ping失败 (${FAIL_COUNT}/${MAX_FAILURES})"
        
        if [ "$FAIL_COUNT" -ge "$MAX_FAILURES" ]; then
            log_message "达到最大失败次数,系统即将关机!"
            shutdown -h now
            exit 0
        fi
    fi
    
    sleep "$CHECK_INTERVAL"
done

修改文件权限

chmod +x /usr/local/ping_monitor/ping_monitor_loop.sh

编写启动服务,实现开机自启执行脚本

ping-monitor.service

[Unit]
Description=Ping Monitor Service #服务名
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/ping_monitor/ping_monitor_loop.sh #脚本所在位置
Restart=always #重启
RestartSec=60
User=root

[Install]
WantedBy=multi-user.target

将ping-monitor.service 放到 /etc/systemd/system 目录下

执行 命令加入自启服务


sudo systemctl daemon-reload
sudo systemctl enable ping-monitor.service
sudo systemctl start ping-monitor.service

基本管理服务命令

# 查看状态
sudo systemctl status *.service

# 查看日志
sudo journalctl -u *.service -f

# 停止服务
sudo systemctl stop *.service

# 禁用服务
sudo systemctl disable *.service