Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # 目标主机
- TARGET="google.com"
- # 允许的最大失败次数
- MAX_FAILURES=20
- # 计数器初始化
- failure_count=0
- echo "--- Ping Test Script Started ---"
- echo "Target: $TARGET"
- echo "Max allowed failures: $MAX_FAILURES"
- # 循环进行ping操作
- while true; do
- echo "--- $(date) --- Attempt $((failure_count + 1)): Pinging $TARGET..."
- # 执行ping命令:
- # -c 1: 只发送一个ICMP请求
- # -W 2: 等待响应的时间为2秒 (timeout)
- # > /dev/null 2>&1: 隐藏标准输出和标准错误,我们只关心退出状态码
- ping -c 1 -W 2 "$TARGET" > /dev/null 2>&1
- # 检查上一个命令的退出状态码 ($?)
- if [ $? -eq 0 ]; then
- # Ping 成功
- echo "Ping successful. Resetting counter."
- failure_count=0
- else
- # Ping 失败
- echo "Ping failed."
- failure_count=$((failure_count + 1))
- echo "Current failure count: $failure_count"
- fi
- # 检查是否达到最大失败次数
- if [ "$failure_count" -ge "$MAX_FAILURES" ]; then
- echo "!!! CRITICAL !!!"
- echo "Maximum failure threshold ($MAX_FAILURES) reached for $TARGET."
- echo "Initiating system reboot..."
- # 执行重启命令 (使用 shutdown -r now 更安全,因为它会先通知系统)
- # 如果需要立即重启,可以使用 'reboot' 或 'shutdown -r now'
- /sbin/shutdown -r now
- # 脚本在这里应该停止执行,因为系统正在重启
- exit 0
- fi
- # 等待一段时间再进行下一次测试 (例如,每10秒测试一次)
- sleep 10
- done
Advertisement
Add Comment
Please, Sign In to add comment