Monitor Your CPU Utilization using Shell Script

Monitor Your CPU Utilization using Shell Script This script will monitor your CPU utilization and send an Email alert to mentioned email address. But which is not real time CPU Utilization. This script required sar command installed in your Linux machine are else you may get error.

# yum install -y sysstat

# sudo apt-get install sysstat

There is a situation where we want to keep an eye on our server CPU utilization because if your server CPU utilization goes HIGH you can’t process any other jobs since it is busy. Before CPU hits HIGH utilization we have to reduce, take an preventing action. Below is the shell script which will alert you when CPU hits 70% utilization, you can also change this as per your requirement by changing the value of “LOAD=”.

Monitor Your CPU Utilization using Shell Script

#!/bin/bash
# Shell script to monitor or watch the high cpu-load
# It will send an email to $ADMIN, if the (cpu load is in %) percentage
# of cpu-load is >= 70%
# If you have any suggestion or question please email to aravikumar48(yet)gmail.com
HOSTNAME=`hostname`
LOAD=70.00
CAT=/bin/cat
MAILFILE=/tmp/mailviews
MAILER=/bin/mail
mailto="EMAILADDRESS"
CPU_LOAD=`sar -P ALL 1 2 |grep 'Average.*all' |awk -F" " '{print 100.0 -$NF}'`
if [[ $CPU_LOAD > $LOAD ]];
then
PROC=`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1`
echo "Please check your processess on ${HOSTNAME} the value of cpu load is $CPU_LOAD % & $PROC" > $MAILFILE
$CAT $MAILFILE | $MAILER -s "CPU Load is $CPU_LOAD % on ${HOSTNAME}" $mailto
fi

How to use above shell script ” Monitor Your CPU Utilization using Shell Script “

Create an file using below command

#touch CpuAlert.sh
#vi CpuAlert.sh

copy above script and paste in CpuAlert.sh file then provide the exective permissions using below command

#chmod +x CpuAlert.sh

Now execute shell script

#sh -x CpuAlert.sh

if your above script output is successful then schedule this script to execute yet every 30mintes. Using below procedure

#crontab -e 
#CPU Utilization Monitoring
*/30 * * * * sh /SCRIPT-PATH/CpuAlert.sh

:wq   <<-- Save & Exit

If you want to execute script every 5 minutes then schedule script as mentioned below

#crontab -e 
#CPU Utilization Monitoring
*/5 * * * * sh /SCRIPT-PATH/CpuAlert.sh

:wq   <<-- Save & Exit

Note: Do not execute the script directly to production. We recommend to test this script in Test/Dev environment before your scheduled to production. Change LOAD=’value’ and mailto=’EMAILADDRESS” parameters before you run above script.

Your feedback is valuable to Us… Please comment your feedback….

Related Articles

Debug Shell_Script Easily

List All Windows Virtual Machines from ESX Server Script

Learn Linux from Scratch

Thanks for your wonderful Support and Encouragement

Stay Connected with us. Learn More and Earn More

Ankam Ravi Kumar

Working as Linux / Storage Administrator L3. Interested in sharing the knowledge.

You may also like...

24 Responses

  1. suresh says:

    I followed your instructions but i unable to any get emails and email server is running on server.

  2. H. T. says:

    -In case of the high cpu- load is >= 70 % for a long time, you need an option (means a switch in your script) to turn off automatic email, otherwise you get every 5 minutes the same email.

    -Use intead awk -F” ” only awk

  3. Mahesh Gedapudi says:

    Great Job. Is it possible to get the another mail when cpu becomes below threshold.

  4. Syed Masood says:

    ++ sar -P ALL 1 2
    CpuAlert.sh: line 12: sar: command not found

    + [[ ” > 70.00 ]]

  5. Abhishek says:

    not getting any email

  6. Niranjan says:

    Hi I was looking for some scripts to monitor Windows NT and 2000 server. We already enabled ping alerts in our SCOM 2012

    My Mail ID: rajvarma.4u@gmail.com

  7. Randhir says:

    Hi,

    As i have tested with below script and form me it working fine.
    1st Step:

    Need to create file as per below script.

    [root@randhir ~]# cat loadaverage.sh
    #!/bin/sh
    #
    NOTIFY=”1″
    TRUE=”1″
    EMAIL=”randhir.thakre@gmail.com another user mail id”
    TEMPFILE=”$(mktemp)”
    FTEXT=’load average:’
    LOAD1MIN=”$(uptime | awk -F “$FTEXT” ‘{ print $2 }’ | cut -d, -f1 | sed ‘s/ //g’)”
    LOAD5MIN=”$(uptime | awk -F “$FTEXT” ‘{ print $2 }’ | cut -d, -f2 | sed ‘s/ //g’)”
    LOAD15MIN=”$(uptime | awk -F “$FTEXT” ‘{ print $2 }’ | cut -d, -f3 | sed ‘s/ //g’)”
    MEMU=”$(free -tom | awk ‘/Total:/ {print “Total memory: “$2” MB\nUsed memory: “$3” MB\nFree memory: “$4″ MB”}’)”
    SUBJECT=”Alert $(hostname) high load average forName of server $LOAD5MIN”
    echo “Server 5 min load average $LOAD5MIN is above notification threshold $NOTIFY” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    echo “Hostname: $(hostname)” >> $TEMPFILE
    echo “Local Date & Time : $(date)” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    echo “Server load for the last five minutes: $LOAD5MIN” >> $TEMPFILE
    echo “Server load for the last fifteen minutes: $LOAD15MIN” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    echo “————————” >> $TEMPFILE
    echo “Memory stats:” >> $TEMPFILE
    echo “————————” >> $TEMPFILE
    echo “$MEMU” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    RESULT=$(echo “$LOAD5MIN > $NOTIFY” | bc)
    if [ “$RESULT” == “$TRUE” ]; then
    # echo true
    /bin/mail -s “$SUBJECT” “$EMAIL” /dev/null 2>&1

    Please test and confirm the status.

    thanks & Regards
    Randhir thakre

  8. Randhir says:

    Below Script :

    #vim loadavrage.sh

    #!/bin/sh
    #
    NOTIFY=”1″
    TRUE=”1″
    EMAIL=”randhir.thakre@gmail.com”
    TEMPFILE=”$(mktemp)”
    FTEXT=’load average:’
    LOAD1MIN=”$(uptime | awk -F “$FTEXT” ‘{ print $2 }’ | cut -d, -f1 | sed ‘s/ //g’)”
    LOAD5MIN=”$(uptime | awk -F “$FTEXT” ‘{ print $2 }’ | cut -d, -f2 | sed ‘s/ //g’)”
    LOAD15MIN=”$(uptime | awk -F “$FTEXT” ‘{ print $2 }’ | cut -d, -f3 | sed ‘s/ //g’)”
    MEMU=”$(free -tom | awk ‘/Total:/ {print “Total memory: “$2” MB\nUsed memory: “$3” MB\nFree memory: “$4″ MB”}’)”
    SUBJECT=”Alert $(hostname) high load average Server name : $LOAD5MIN”
    echo “Server 5 min load average $LOAD5MIN is above notification threshold $NOTIFY” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    echo “Hostname: $(hostname)” >> $TEMPFILE
    echo “Local Date & Time : $(date)” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    echo “Server load for the last five minutes: $LOAD5MIN” >> $TEMPFILE
    echo “Server load for the last fifteen minutes: $LOAD15MIN” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    echo “————————” >> $TEMPFILE
    echo “Memory stats:” >> $TEMPFILE
    echo “————————” >> $TEMPFILE
    echo “$MEMU” >> $TEMPFILE
    echo ” ” >> $TEMPFILE
    RESULT=$(echo “$LOAD5MIN > $NOTIFY” | bc)
    if [ “$RESULT” == “$TRUE” ]; then
    # echo true
    /bin/mail -s “$SUBJECT” “$EMAIL” /dev/null 2>&1

    Thanks & Regards
    Randhir Thakre

  9. Thanks for the script. SAR command works for me. You save my time.
    Keep it up 🙂

  10. Balaram says:

    Hi Aravikumar,
    Very useful script.. But some how this script fails when the CPU load is 100%.

    Regards,
    Balaram

    • Let me verify Balaram, Thanks for the Update. Stay tune for more updates.

    • Yogesh says:

      Rght term would be “CPU Usage” as you guys are collecting stats through SAR.. If CPU is 100% utilized , your script “being a bunch of shell processes” will go to wait queue.

      Reduce the frequency of this script from 30 mins to 01 mins , if you don’t have any functional monitoring system. Else running this script every minute is not going to load your system.

  11. Suraj says:

    It’s working fine to me. Thanks you

  12. socialawarnesssite says:

    I couldn’t understand what this line will give – awk -F” ” ‘{print 100.0 -$NF}’`?
    Please help me.

  13. Sudhakar Nunna says:

    could not understand what the following AWK command will do “awk -F” ” ‘{print 100.0 -$NF}’`”

    • ARK says:

      [root@Arkit-Serv ~]# sar -P ALL 1 2 |grep ‘Average.*all’
      Average: all 0.00 0.00 0.00 0.00 0.00 100.00
      [root@Arkit-Serv ~]# sar -P ALL 1 2 |grep ‘Average.*all’ |awk -F” ” ‘{print 100.0 -$NF}’
      0.25

      Maybe above output will give an idea what -$NF will do. NF Number of Fields in awk.

  14. Niranjan says:

    Any one please send me using “sar” cpu load, memory, io, network usage script i need..??

  15. Jay says:

    How to modify the script in such a way that is just monitors just one specific process ?? Could you please help.

  16. Ashish singh says:

    I want the above same script on one host which will fetch me CPU utilization for multiple host and output should be in tabular format.
    E.g.
    Sr.no hostname cpu utilization status .

    In the column status the color should be green for normal condition and red for high utilization

    • ARK says:

      Hi Ashish, Simple solution for monitoring multiple hosts using above script. Create one NFS share from one server and mount the same to all the hosts,save script output to NFS mount point.

Leave a Reply