![如何创建一个 perl 脚本来检查系统状态(CPU、RAM、HDD)并发送警报邮件?](https://linux22.com/image/1126396/%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%20perl%20%E8%84%9A%E6%9C%AC%E6%9D%A5%E6%A3%80%E6%9F%A5%E7%B3%BB%E7%BB%9F%E7%8A%B6%E6%80%81%EF%BC%88CPU%E3%80%81RAM%E3%80%81HDD%EF%BC%89%E5%B9%B6%E5%8F%91%E9%80%81%E8%AD%A6%E6%8A%A5%E9%82%AE%E4%BB%B6%EF%BC%9F.png)
该脚本用于添加到 cron 选项卡。shell 脚本的流程应该是这样的。1. 检查 CPU 状态。2. 检查 RAM 使用情况。3. 检查 HDD 使用情况。4. 如果其中任何一个超过阈值,则向收件人发送警报邮件。(例如 90%)
@matches=grep {$_ >90} (
df -H
=~/(\S+%)/g);打印“@matches \ n”;
如果高于 90%,则返回“df _H”的输出
对于 RAM,
免费 | grep Mem | awk'{print $3/$2 * 100.0}'
上述命令以百分比形式返回 RAM 使用情况
现在,应该将其与 80% 的阈值进行比较。然后,如果上述任何值 [HDD/RAM] 偏高,程序应发送一封邮件,其中附加“top”命令的结果,以显示 CPU 使用率。
请帮忙。
这将被添加到 cron 选项卡中,以便以相等的间隔运行。请更新。
答案1
开始吧。
创建load.sh
脚本
nano /path/load.sh
#!/bin/bash
#we use output from "uptime" i "w" to have load on 5 min
UPTIME=`uptime`;
W=`w`;
RAM=`free -m`;
DATE=`date`;
sleep 3
DF=`df -h`
sleep 3
echo "######################################" >> /var/log/load-result/load_log
echo "$DATE" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "UPTIME:" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "$UPTIME" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "W COMMAND:" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "$W" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "FREE RAM:" >> /var/log/load-result/load_log
echo "$RAM" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "FREE SPACE:" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "$DF" >> /var/log/load-result/load_log
echo "" >> /var/log/load-result/load_log
echo "#####################################" >> /var/log/load-result/load_log
授予脚本 X 权限
chmod 777 /path/load.sh
创建用于存储日志文件的目录
sudo mkdir /var/log/load-result
创建脚本来发送邮件
nano /path/mail.sh
mail -s Load_From_PC [email protected] < /var/log/load-result/load_log
给予 Xmail.sh
chmod 777 /path/mail.sh
创建 cron 作业
sudo crontab -e
*/5 * * * * /path/load.sh
00 11 * * * /path/mail.sh
load.sh
将每 5 分钟执行一次,脚本结果将添加到日志文件的底部。
mail.sh
每天 11:00 触发
您可以更改时间...