Friday 23 September 2016

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.

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=”.

#!/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 your mail address HOSTNAME=`hostname` LOAD=70.00 CAT=/bin/cat MAILFILE=/tmp/mailviews MAILER=/bin/mail mailto="yourmailaddress@gmail.com" 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 executive 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….


No comments: