centos7写一个监控系统的shell,要求如下 cpu使用率超过80%(Shell变量单独配置)并且持续60秒钟(Shell变量单独配置)以上使用Curl post json方式调用http://...

该bash脚本用于监控服务器的CPU、内存和磁盘使用情况,当超过预设的使用率阈值且持续时间超过设定时间时,将发送包含服务器IP、当前使用率、持续时间和占用资源最多的进程列表的JSON数据到指定URL进行报警。
摘要由CSDN通过智能技术生成

``` #!/bin/bash

cpu_usage_threshold=80 cpu_duration_threshold=60 memory_usage_threshold=70 memory_duration_threshold=70 disk_usage_threshold=90 disk_duration_threshold=90 interval=5 server_ip=$(ip addr show | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d/ -f1)

while true; do current_time=$(date +%s)

# CPU Usage
cpu_usage=$(top -b -n 1 | awk '/Cpu/ {print $2}' | cut -d. -f1)
if [ $cpu_usage -gt $cpu_usage_threshold ]; then
    cpu_start_time=${cpu_start_time:-$current_time}
    if [ $((current_time-cpu_start_time)) -gt $cpu_duration_threshold ]; then
        top_cpu_processes=$(ps -eo pid,%cpu,comm --sort=-%cpu | head -n 4 | awk '{print $3}')
        data=$(printf '{"server_ip":"%s","current_usage":%d,"duration":%d,"top_processes":["%s"]}' "$server_ip" "$cpu_usage" "$((current_time-cpu_start_time))" "$top_cpu_processes")
        curl -H "Content-Type: application/json" -X POST -d "$data" http://aaa.com
        unset cpu_start_time
    fi
else
    unset cpu_start_time
fi

# Memory Usage
memory_usage=$(free | awk '/Mem/ {printf("%.0f"), $3/$2*100}')
if [ ${memory_usage%.*} -gt $memory_usage_threshold ]; then
    memory_start_time=${memory_start_time:-$current_time}
    if [ $((current_time-memory_start_time)) -gt $memory_duration_threshold ]; then
        top_memory_processes=$(ps -eo pid,%mem,comm --sort=-%mem | head -n 4 | awk '{print $3}')
        data=$(printf '{"server_ip":"%s","current_usage":%d,"duration":%d,"top_processes":["%s"]}' "$server_ip" "$memory_usage" "$((current_time-memory_start_time))" "$top_memory_processes")
        curl -H "Content-Type: application/json" -X POST -d "$data" http://aaa.com
        unset memory_start_time
    fi
else
    unset memory_start_time
fi

# Disk Usage
disk_usage=$(df -h | awk '$NF=="/"{printf("%.0f"), $5}')
if [ ${disk_usage%.*} -gt $disk_usage_threshold ]; then
    disk_start_time=${disk_start_time:-$current_time}
    if [ $((current_time-disk_start_time)) -gt $disk_duration_threshold
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值