Friday, April 13, 2012

Write a shell script to monitor CPU usage and send an e-mail

This is a small shell script to monitor CPU usage. IF the cpu usage is more than 75% then send an e-mail to respective teams.

#!/bin/bash
#Author: Surendra Kumar Anne
#Purpose: To monitor the CPU usage
#Date:2012-04-13
SUBJECT="WARNING CPU USAGE HIGH"

TO=yourteam@companiesemailcom
MESSAGE=/tmp/messages
echo "#######################" > $MESSAGE

echo "CPU statistics as follows.." >> $MESSAGE

mpstat > $MESSAGE
echo "#######################" >> $MESSAGE
CPU_USAGE=$(top -b -n1 | awk '/^Cpu/ {print $2}' | cut -d\. -f1)
[ $CPU_USAGE -gt 75 ] && mail -s "$SUBJECT" "$TO" < $MESSAGE

Once the above script is writen and given execute permissions keep this script in crontab which runs for every 1min or 5mins.
0-59 * * * *  bash /pathtoscript.sh




3 comments:

  1. Hi,

    your script is wrong, you should append text to message using ">>"

    Something like this (I added top 5 process):

    echo "######### RDONATO SCRIPT ##############" > $MESSAGE

    echo "CPU statistics as follows.." >> $MESSAGE

    mpstat >> $MESSAGE
    echo "TOP 5 Process" >> $MESSAGE
    echo "#######################" >> $MESSAGE
    ps aux | sort -k 3,3 | tail -n 5 >> $MESSAGE
    echo "#######################" >> $MESSAGE
    CPU_USAGE=$(top -b -n1 | awk '/^Cpu/ {print $2}' | cut -d\. -f1)
    [ $CPU_USAGE -gt 50 ] && mail -s "$SUBJECT" "$TO" < $MESSAGE

    ReplyDelete
  2. Simple script , thanks for sharing

    rj

    ReplyDelete
  3. hiii, please help me for this task...
    perl scrip to check the memory and cpu usage, if this usage goes beyond 50%. it should send a mail to me and my boss mail id......
    if anyone knows please gives feedback........

    thanks,,,,,

    ReplyDelete