#小白记录中

                                         理清思路是成功的90%

一、掌握要点

        本次脚本使用了top,awk,grep,cut,df,free,反引号,比较符,位数。

二、实施操作

1.确认多少容量算告警,告警邮件,根据需要修改默认值

#!/bin/bash
#设置告警容量阈值
cpu_max=80
mem_max=85
disk_max=85
mail="lsj.com"

2.获取当前系统的cpu,内存,硬盘容量值

get_cpu_value(){
    cpu_value=`top -bn1|grep Cpu|awk '{print $2}'|cut -d'.' -f1`
    echo "cpu_value"
}
get_mem_value(){
    mem_value=`free -m|grep 'Mem'|awk '{printf("%.0f",$3/$2*100)}'`
    echo "mem_value"
}
get_disk_value(){
    disk_value=`df -Th /|awk 'NR==2{print $6}'|cut -d '%' -f1`
    echo "disk_value"
}

结果如图:

cpu:

内存:

硬盘:

3,编写告警模版

sent_mail(){
    local resource=$1
    local usage=$2
    local usmax=$3
    echo "警告:${resource}的使用率${usage}超过阈值${usmax}
    mail -s "系统资源告警" $mail
}

4.判断cpu,内存,硬盘比重,写主方法

echo "start资源监控"
   ##cpu判定
   cpu=$(get_cpu_value)
   if [ "$cpu" -gt "$cpu_max"] ;then
        echo "cpu使用过高"
        sent_mail "CPU" $cpu $cpu_max
    else
        echo "使用正常"
    fi
   ##mem判定
   mem=$(get_mem_value)
   if [ "$mem" -gt "$mem_max"] ;then
        echo "mem使用过高"
        sent_mail "mem" $mem $mem_max
    else
        echo "使用正常"
    fi
   ##disk判定
   disk=$(get_disk_value)
   if [ "$disk" -gt "$disk_max"] ;then
        echo "disk使用过高"
        sent_mail "disk" $disk $disk_max
    else
        echo "使用正常"
    fi

5.定时告警

# 定时执行
if [ "$1" == "daemon" ]; then
    while true; do
        main
        sleep 60  # 每分钟检查一次
    done
else
    main
fi

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐