#!/bin/bash

定义需要检查的网站

websites=('wwwbdsdthsehzaidu.pw' 'garegn.pw' 'www.sysu.ecn')

定义重试次数

max_retry=5

定义连续失败次数达到多少次后重新启动服务器

max_failures=3

定义检查间隔时间,单位是秒

interval=5

restart_command="systemctl reboot"

定义日志文件

log_ok_file="/var/log/gfw-status-ok.log" log_error_file="/var/log/gfw-status-error.log"

整个函数用于tcping测试网站是否可用

function test_website { echo -e "\033[36m[$(date '+%Y-%m-%d %H:%M:%S')] - 正在测试网站: $1\033[0m" for ((i=1; i<=$max_retry; i++)); do hping3_result=$(hping3 -S $1 -c 5 -p 443 > /dev/null 2>&1) if [ $? -eq 0 ]; then echo -e "\033[32m[$(date '+%Y-%m-%d %H:%M:%S')] - 网站 $1 可用\033[0m" echo "[$(date '+%Y-%m-%d %H:%M:%S')] - 网站 $1 可用" >> $log_ok_file return 0 else echo -e "\033[31m[$(date '+%Y-%m-%d %H:%M:%S')] - 网站 $1 不可用 - 第 $i 次重试\033[0m" echo "[$(date '+%Y-%m-%d %H:%M:%S')] - 网站 $1 不可用 - 第 $i 次重试" >> $log_error_file fi sleep $interval done return 1 }

定义函数,用于重新启动服务器

function reboot_server { echo -e "〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓" echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] - 所有网站都不可用 - 正在重新启动服务器" echo -e "〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓" $restart_command }

主循环

while true; do failure_count=0 for website in "${websites[@]}"; do if test_website "$website"; then failure_count=0 else ((failure_count++)) if [ $failure_count -ge $max_failures ]; then echo -e "\033[31m[$(date '+%Y-%m-%d %H:%M:%S')] - $website 连续 $failure_count 次不可用\033[0m" # 添加重试逻辑 for ((j=1; j<=3; j++)); do echo -e "\033[36m[$(date '+%Y-%m-%d %H:%M:%S')] - 正在重试 $website - 第 $j 次\033[0m" if test_website "$website"; then failure_count=0 break else ((failure_count++)) fi sleep $interval done if [ $failure_count -ge $max_failures ]; then break fi fi fi done if [ $failure_count -ge $max_failures ]; then echo -e "\033[33m[$(date '+%Y-%m-%d %H:%M:%S')] - 持续测试 3 个网站均无法访问\033[0m" reboot_server >> $log_error_file 2>&1 exit 0 fi sleep $interval done

监控网站状态,持续不可用则重启服务器 (附带重试机制)

原文地址: https://www.cveoy.top/t/topic/mRlQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录