Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SHELL

CPU usage alert generator bash script

PATHS="/"
Hname=$(hostname | awk -F. '{print $1}')
criticalpr=98
warningpr=80
logloc="cpuusagehist"

criticalmail="ptclhr@gmail.com"
warmail="ptcladmin@gmail.com"

sudo mkdir -p /var/log/$logloc
logfilename=/var/log/$logloc/$Hname.`date +%u.%I.%m:%y`.log
sudo touch $logfilename

for i in $PATHS
do
        cpuload=`top -b -n 2 -d1 | grep 'Cpu(s)' | tail -n1 | awk '{print $2}' | awk -F . '{print $1}'`

if [ -n $criticalpr -a -n $warningpr ]; then
      if [ "$cpuload" -ge "$warningpr" -a "$cpuload" -le "$criticalpr" ]; then
        
        echo "Warning! -- Cpuload: $cpuload% on Host: $Hname -- `date "+%I:%M:%S:%F"`" | sudo tee -a $logfilename &>/dev/null
        echo "Warning! -- Cpuload: $cpuload% on Host: $Hname" | mail -s "Reaching $cpuload CPUload" $warmail
        exit 1

elif [ "$cpuload" -ge "$criticalpr" ]; then 
        
        echo "Critical! -- Cpuload: $cpuload% on Host: $Hname -- `date "+%I:%M:%S:%F"`" | sudo tee -a $logfilename &>/dev/null
        echo "Critical! -- Cpuload: $cpuload% on Host: $Hname" | mail -s "Reaching $cpuload CPUload" $criticalmail
        exit 2

else

        echo "OK -- Cpuload: $cpuload% on Host: $Hname -- `date "+%I:%M:%S:%F"`" | sudo tee -a $logfilename &>/dev/null
        exit 0
fi
fi
done
 
PREVIOUS NEXT
Tagged: #CPU #usage #alert #generator #bash #script
ADD COMMENT
Topic
Name
1+9 =