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.

Real Time CPU Load Monitoring Shell Script

Below is the script updated recently to capture real time CPU Utilization and store the historical Data into /var/log/cpuhistory/ directory path

#!/bin/bash
##Author: Ankam Ravi Kumar
##Email ID: admin@arkit.co.in
##Updated: 13th Nov 2017
##Site: https://arkit.co.in

HOSTNAME=`hostname`
PATHS="/"
WARNING=90
CRIT=98
CAT=/bin/cat
MAILER=/bin/mail
CRITmailto="YOUREMAIL@DOMAIN.COM"
mailto="YOUREMAIL@DOMAIN.COM"
mkdir -p /var/log/cpuhistory
LOGFILE=/var/log/cpuhistory/hist-`date +%h%d%y`.log
touch $LOGFILE

for path in $PATHS
do
CPU_LOAD=`top -b -n 2 -d1 | grep "Cpu(s)" | tail -n1 | awk '{print $2}' |awk -F. '{print $1}'`
if [ -n "$WARNING" -a -n "$CRIT" ]; then
 if [ "$CPU_LOAD" -ge "$WARNING" -a "$CPU_LOAD" -lt "$CRIT" ]; then
 echo " `date "+%F %H:%M:%S"` WARNINGING - $CPU_LOAD on Host $HOSTNAME" >> $LOGFILE
echo "CPU Load is Warning $CPU_LOAD on $HOSTNAME" | $MAILER -s "CPU Load is Warning $CPU_LOAD on $HOSTNAME" $mailto
exit 1
elif [ "$CPU_LOAD" -ge "$CRIT" ]; then
 echo "`date "+%F %H:%M:%S"` CRITICAL - $CPU_LOAD on $HOSTNAME" >> $LOGFILE
echo "CPU Load is Critical $CPU_LOAD on $HOSTNAME" | $MAILER -s "CPU Load is Critical $CPU_LOAD on $HOSTNAME" $CRITmailto
exit 2
else
echo "`date "+%F %H:%M:%S"` OK - $CPU_LOAD on $HOSTNAME" >> $LOGFILE
exit 0
fi
fi
done

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

Ankam Ravi Kumar

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

29 Responses

  1. suresh says:

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

    • Can you verify below command
      mail -s “testing” your@emailaddress test

      From above command if you receive an email then script also will work.

      • blank Ashes Limbu says:

        Hello Ravi, I modified the script as per my requirement but while testing (bash cpuusagealert.sh) its says command not found. Not sure what is the issue, though it is generating log file something like this:
        2021-09-02 %H:%M:%S
        2021-09-02 08:41:48 OK – 0 on
        2021-09-02 08:44:00 OK – 1 on
        2021-09-02 08:45:56 OK – 0 on
        2021-09-02 08:47:30 OK – 41 on
        2021-09-02 08:48:33 OK – 60 on
        2021-09-02 08:49:06 OK – 0 on

        I am also not sure what should be put under PATHS=? though hostname info i have.
        If you could help me out will be a huge favor.

        #!/bin/sh
        HOSTNAME=`10.84.22.63`
        PATHS=”/”
        WARNING=70
        CRIT=80
        CAT=/bin/cat
        MAILER=/bin/mail
        CRITmailto=”a.limbu@abcd.com”
        mailto=”ashes.limbu@abcd.com”
        mkdir -p /home/c28320/cpuhistory
        LOGFILE=/home/c28320/cpuhistory/hist-`date +%h%d%y`.log
        touch $LOGFILE
        for path in $PATHS
        do
        CPU_LOAD=`top -b -n 2 -d1 | grep “Cpu(s)” | tail -n1 | awk ‘{print $2}’ |awk -F. ‘{print $1}’`
        if [ -n “$WARNING” -a -n “$CRIT” ]; then
        if [ “$CPU_LOAD” -ge “$WARNING” -a “$CPU_LOAD” -lt “$CRIT” ]; then
        echo ” `date “+%F %H:%M:%S”` WARNINGING – $CPU_LOAD on Host $HOSTNAME” >> $LOGFILE
        echo “CPU Load is Warning $CPU_LOAD on $HOSTNAME” | $MAILER -s “CPU Load is Warning $CPU_LOAD on $HOSTNAME” $mailto
        exit 1
        elif [ “$CPU_LOAD” -ge “$CRIT” ]; then
        echo “`date “+%F %H:%M:%S”` CRITICAL – $CPU_LOAD on $HOSTNAME” >> $LOGFILE
        echo “CPU Load is Critical $CPU_LOAD on $HOSTNAME” | $MAILER -s “CPU Load is Critical $CPU_LOAD on $HOSTNAME” $CRITmailto
        exit 2
        else
        echo “`date “+%F %H:%M:%S”` OK – $CPU_LOAD on $HOSTNAME” >> $LOGFILE
        exit 0
        fi
        fi
        done

  2. blank 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. blank Mahesh Gedapudi says:

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

  4. blank Syed Masood says:

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

    + [[ ” > 70.00 ]]

  5. blank Abhishek says:

    not getting any email

  6. blank 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. blank 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. blank 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. blank 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.

    • blank 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. blank Suraj says:

    It’s working fine to me. Thanks you

  12. blank socialawarnesssite says:

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

  13. blank Sudhakar Nunna says:

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

    • blank 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. blank Niranjan says:

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

  15. blank Jay says:

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

  16. blank 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

    • blank 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.

  17. blank Pranesh Kulkarni says:

    HI Ravi, Thanks for the script we are using this kind of format to send mail ,
    mail -v -r “testuser@example.com” \
    -s “Test mail from Linux” \
    -S smtp=”ip addr” \
    -S smtp-use-starttls \
    -S smtp-auth=login \
    -S smtp-auth-user=”testuser” \
    -S smtp-auth-password=”junk” \
    -S ssl-verify=ignore \
    -S nss-config-dir=”/etc/pki/nssdb/” \
    userrr@example.com

    so how to encorporate this in your script, Requesting you to kindly help on this

  18. blank Muthukumar says:

    Hi Bro,
    I need your help, If the CPU utilisation is more than 3 mins.. then only send the email. In that scenario how to write the script.
    Thanks,

  19. blank Muthukumar says:

    Hi Ankam Ravi Kumar,

    I want to monitor cpu usage if 80% continuously in 3 mins… In that scenario.. how to write the script.
    Thanks

  20. blank b1980 says:

    Hi ARK,

    If possible can provide the description to each step for new in scripting like me to hard to understand.

    thanks

Leave a Reply

Your email address will not be published. Required fields are marked *