Linux服务器超过资源占用阈值自动重启,并通知钉钉机器人(CPU/Memory)

1718184088605.png

在Linux服务器上实现自动重启的脚本可以使用Shell脚本编写并结合cron作业调度器

如果你在运行脚本时出现了 bc: command not found 的错误,这说明你的系统中没有安装 bc 工具,
bc 是一个用于数学计算的命令行工具,我们需要使用它来进行浮点数比较。

# Debian/Ubuntu
sudo apt-get install bc

# CentOS/RHEL
sudo yum install bc

创建脚本

创建一个Shell脚本文件,比如 auto_restart.sh

脚本会在 CPU 或内存使用率超过阈值时发送一条通知,

并在重启服务器时发送另一条通知。

#!/bin/bash

# 重启条件为 30分钟内CPU或内存资源占用超过80%

# 定义 CPU 和内存的阈值
cpu_threshold=80
mem_threshold=80

# 定义重启间隔时间
restart_interval=1800  # 30分钟,单位为秒

# 钉钉机器人的 Webhook 地址
dingding_webhook="https://oapi.dingtalk.com/robot/send?access_token=your_access_token"

# 发送钉钉通知的函数
send_dingding_notification() {
    local message="$1"
    curl -H "Content-Type: application/json" -X POST -d "{\"msgtype\": \"text\", \"text\": {\"content\": \"$message\"}}" $dingding_webhook
}

echo "Auto Reboot Script: Monitoring CPU and memory usage..."

# 循环检测 CPU 和内存使用率
while true; do
    # 获取当前 CPU 使用率
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')

    # 获取当前内存使用率
    mem_usage=$(free | awk '/Mem/{printf("%.2f"), $3/$2*100}')

    # 显示当前 CPU 和内存使用率
    echo "Current CPU usage: $cpu_usage%"
    echo "Current memory usage: $mem_usage%"

    # 如果 CPU 或内存使用率超过阈值,则开始计时
    if [ $(echo "$cpu_usage > $cpu_threshold || $mem_usage > $mem_threshold" | bc) -eq 1 ]; then
        echo "CPU or memory usage is above threshold. Monitoring for continuous high usage..."
        # 此处通知可以删除,只要达到阈值就会通知
        send_dingding_notification "CPU or memory usage is above threshold. Monitoring for continuous high usage..."

        start_time=$(date +%s)

        # 在重启间隔时间内持续检测 CPU 和内存使用率
        while true; do
            current_time=$(date +%s)
            elapsed_time=$((current_time - start_time))

            # 如果持续时间超过重启间隔时间,则重启服务器
            if [ $elapsed_time -ge $restart_interval ]; then
                echo "CPU or memory usage has been continuously high for $((restart_interval / 60)) minutes. Restarting the server..."

                # 此处通知只在重启时调用
                send_dingding_notification "CPU or memory usage has been continuously high for $((restart_interval / 60)) minutes. Restarting the server..."
                shutdown -r now
                break
            fi

            # 检测 CPU 和内存使用率
            cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
            mem_usage=$(free | awk '/Mem/{printf("%.2f"), $3/$2*100}')

            # 如果 CPU 和内存使用率都低于阈值,则跳出循环
            if [ $(echo "$cpu_usage <= $cpu_threshold && $mem_usage <= $mem_threshold" | bc) -eq 1 ]; then
                break
            fi

            sleep 10  # 每10秒检测一次
        done
    fi

    # 每5分钟显示一次当前使用率
    sleep 300  # 300秒 = 5分钟
done

授予脚本执行权限

chmod +x auto_restart.sh

创建服务单元

创建一个服务单元文件,比如 /etc/systemd/system/auto_reboot_script.service,内容如下:

替换 /path/to/your/auto_reboot_script.sh 为你的脚本的实际路径。

[Unit]
Description=Auto Reboot Script Service
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash /path/to/your/auto_reboot_script.sh
Restart=always

[Install]
WantedBy=multi-user.target

启动服务

sudo systemctl enable auto_reboot_script.service
sudo systemctl start auto_reboot_script.service

检查运行状态

sudo systemctl status auto_reboot_script.service

1718183969694.png

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值