Linode 寄信提示 CPU 異常使用率,超過 90% 使用率,一次好幾小時。根據網路拼湊、修改出腳本來定期監控 CPU 使用率。原則上五分鐘監控一次,使用率超過 70% 觸發 log,log 寫在監控腳本同目錄下。
cpuuse=$(cat /proc/loadavg | awk '{print $3}'|cut -f 1 -d ".")
if [ "$cpuuse" -ge 70 ]; then
MESSAGE=$(date +%s).log
echo "CPU current usage is: $cpuuse%" >> $MESSAGE
echo "" >> $MESSAGE
echo "+------------------------------------------------------------------+" >> $MESSAGE
echo "Top 20 processes which consuming high CPU" >> $MESSAGE
echo "+------------------------------------------------------------------+" >> $MESSAGE
echo "$(top -bn1 | head -20)" >> $MESSAGE
echo "" >> $MESSAGE
echo "+------------------------------------------------------------------+" >> $MESSAGE
echo "Top 10 Processes which consuming high CPU using the ps command" >> $MESSAGE
echo "+------------------------------------------------------------------+" >> $MESSAGE
echo "$(ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10)" >> $MESSAGE
else
echo "CPU usage OK"
fi
腳本存好,chmod +x 以後下 crontab
crontab -e
*/10 * * * * /bin/bash /opt/scripts/cpu-alert.sh
以目前使用者身份執行腳本一次(不一定跟 cron 同使用者!),確認腳本沒問題
crontab -l | grep -v '^#' | cut -f 6- -d ' ' | while read CMD; do eval $CMD; done
全文連結