用于监控 CPU 使用情况的 shell 脚本,并对消耗 CPU 最多的前 5 个进程发出警报

用于监控 CPU 使用情况的 shell 脚本,并对消耗 CPU 最多的前 5 个进程发出警报

每当 CPU 利用率超过 70% 时,我需要发送电子邮件?我该怎么做?当 CPU 利用率超过 70% 时,我还需要获取前 5 个进程的启动命令和进程名称,类似于 htop 给出的

在此处输入图片描述

我怎样才能用 shell 脚本做到这一点?

答案1

每当 CPU 利用率超过 70% 时我需要发送电子邮件吗?

我建议您使用现有的监控插件来实现此目的。插件 check_cpu_stats 支持 CPU 使用率(而非负载)的阈值。此插件有几个不同版本,您可以在此处找到一个示例:https://github.com/Reamer/check_cpu_stats

使用非常简单:

$ /usr/lib/nagios/plugins/check_cpu_stats.sh -w 70,70,70 -c 80,80,80
CPU STATISTICS OK : user=7.60% system=2.35%, iowait=0.08%, idle=86.94%, nice=3.02%, steal=0.00% | CpuUser=7.60%;70;80;0; CpuSystem=2.35%;70;80;0; CpuIowait=0.08%;70;80;0; CpuIdle=86.94%;0;0;0; CpuNice=3.02%;0;0;0; CpuSteal=0.00%;0;0;0;

警告阈值设置为用户、系统和 iowait 的 CPU 使用率 70%。临界阈值设置为用户、系统和 iowait 的 CPU 使用率 80%。当然,您也可以根据您的环境调整阈值。

关于警报部分:当然,最好的情况是,如果您已经在现有监控中拥有此主机/机器。但您也可以独立使用插件并发送警报。示例:

/usr/lib/nagios/plugins/check_cpu_stats.sh -w 70,70,70 -c 80,80,80 > /dev/null; if [[ $? -gt 0 ]]; then echo "alert" | mailx -s "cpu alert" [email protected]; else echo "no alert"; fi

我还需要获取前 5 个进程的启动命令和进程名称

要获取前 5 个进程(按 CPU 使用率排序),可以使用以下命令(来源:https://unix.stackexchange.com/questions/13968/show-top-five-cpu-assuming-processes-with-ps):

ps aux | sort -nrk 3,3 | head -n 5

现在你可以将监控插件和流程输出结合起来:

/usr/lib/nagios/plugins/check_cpu_stats.sh -w 70,70,70 -c 80,80,80 > /dev/null; if [[ $? -gt 0 ]]; then echo "$(ps aux | sort -nrk 3,3 | head -n 5)" | mailx -s "cpu alert" [email protected]; else echo "no alert"; fi

相关内容