这个脚本做了一些优化并且添加了以下功能

1.当CPU占用超过50%并且持续10秒以上,开始向TG发送警报通知.
2.当CPU占用超过50%并且持续120秒以上,执行停止apache和php命令.
3.当CPU占用恢复正常状态,即50%以下并且持续120秒以上,执行重新启动apache和php的命令.

#!/bin/bash

# Telegram Bot API Token
TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
# Your Telegram chat ID
CHAT_ID="YOUR_TELEGRAM_CHAT_ID"

# Apache and PHP commands
APACHE_STOP="/etc/init.d/httpd stop"
PHP_STOP="/etc/init.d/php-fpm-74 stop"
APACHE_START="/etc/init.d/httpd restart"
PHP_START="/etc/init.d/php-fpm-74 restart"

# Initialize counters
count=0
stop_count=0
start_count=0
restart_flag=0

while true; do
    # 使用sar获取CPU使用率数据
    cpu_usage=$(sar -u 1 1 | tail -n 1 | awk '{print 100 - $NF}')

    # 检查CPU使用率是否超过50%
    if (( $(echo "$cpu_usage > 50" | bc -l) )); then
        ((count++))
        ((stop_count++))
        start_count=0
        restart_flag=0
        # 检查连续时间是否达到10秒
        if ((count >= 10)); then
            # 发送警报到Telegram
            message="⚠️ CPU 使用率超过50%!当前使用率为 $cpu_usage %"
            curl -s -X POST https://api.telegram.org/bot$TOKEN/sendMessage -d chat_id=$CHAT_ID -d text="$message"
            count=0
        fi
        # 检查连续时间是否达到120秒
        if ((stop_count >= 120)); then
            # 停止Apache和PHP
            $APACHE_STOP
            $PHP_STOP
            stop_count=0
        fi
    else
        if ((restart_flag == 0)); then
            ((start_count++))
            # 检查连续时间是否达到120秒
            if ((start_count >= 120)); then
                # 重启Apache和PHP
                $APACHE_START
                $PHP_START
                start_count=0
                restart_flag=1
            fi
        fi
    fi
done
Last modification:December 31st, 2023 at 11:46 am