用shell判断cpu的使用率是否超过98%,如果超过90%获取cpu使用率最高的进程信息,如果不超过输出cpu使用率前十的进程信息
/mnt/zzy/data/scripts/cpumonitor.sh
#!/bin/bash
# 获取CPU使用率(注意这里用了top命令)
#logfile=/root/syszzy.log
logfile=/mnt/zzy/syszzy.log
cpu_usage=$(top -b -n1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'.' -f1)
if [ "$cpu_usage" -gt 98 ]; then
# 如果超过98%,获取CPU使用率最高的进程信息
top_processes=$(top -b -n1 | tail -n +8 | sort -k9rn | head)
echo "CPU usage is over 98%, top processes:" >> $logfile
echo "---------------------`date`-----------------" >> $logfile
echo "$top_processes" >> $logfile
elif [ "$cpu_usage" -gt 90 ]; then
# 如果超过90%但不到98%,输出CPU使用率前十的进程信息
top_processes=$(top -b -n1 | tail -n +8 | sort -k9rn | head)
echo "CPU usage is over 90%, top processes:" >> $logfile
echo "---------------------`date`-----------------" >> $logfile
echo "$top_processes" >> $logfile
#else
# 如果不超过90%,输出CPU使用率前十的进程信息
# top_processes=$(top -b -n1 | tail -n +8 | sort -k9rn | head )
#echo "CPU usage is below 90%, top processes:" >> $logfile
#echo "---------------------`date`-----------------" >> $logfile
#echo "$top_processes" >> /root/syszzy.log
fi