lnux环境中用shell脚本监控http进程的cpu和内存使用情况,如果到达阈值则发送报警邮件
时间: 2024-02-15 15:03:03 浏览: 48
好的,可以使用下面的Shell脚本来监控http进程的CPU和内存使用情况,并在达到阈值时发送报警邮件。这个脚本可以在Linux环境下运行。
```bash
#!/bin/bash
# 进程名
process_name="httpd"
# CPU、内存阈值(百分比)
cpu_threshold=90
mem_threshold=90
# 收件人邮箱地址
to_email="your_email@example.com"
# 获取进程PID
pid=$(pgrep $process_name)
# 获取进程CPU、内存使用情况
cpu_usage=$(ps -p $pid -o %cpu | grep -v CPU | awk '{print $1}')
mem_usage=$(ps -p $pid -o %mem | grep -v MEM | awk '{print $1}')
# 判断使用情况是否超过阈值
if [[ $(echo "$cpu_usage > $cpu_threshold" | bc -l) -eq 1 ]]; then
echo "CPU usage of $process_name is over $cpu_threshold%" | mail -s "CPU Alert" $to_email
fi
if [[ $(echo "$mem_usage > $mem_threshold" | bc -l) -eq 1 ]]; then
echo "Memory usage of $process_name is over $mem_threshold%" | mail -s "Memory Alert" $to_email
fi
```
将上面的代码保存为一个Shell脚本文件,比如`monitor_http.sh`,然后给该文件执行权限:
```
chmod +x monitor_http.sh
```
之后,可以使用cron定时任务来定时执行该脚本,比如每隔5分钟执行一次。编辑cron任务:
```
crontab -e
```
添加下面的一行,表示每隔5分钟执行一次`monitor_http.sh`脚本:
```
*/5 * * * * /path/to/monitor_http.sh
```
修改`/path/to/monitor_http.sh`为实际脚本文件的路径。之后,当http进程的CPU或内存使用情况超过阈值时,您将会收到报警邮件。