2

I was wondering if anyone could help with the reasons that this is not triggering properly

HOSTNAME=`hostname -s`
LOAD=25.00
CAT=/bin/cat
MAILFILE=/home/jboss/monitor.mail
MAILER=/bin/mail
mailto="bob@bob.bob"
CPU_LOAD=`sar -P ALL 1 10 |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 -e "Please check processes on ${HOSTNAME} the value of cpu load is $CPU_LOAD%.
Highest process is: $PROC" > $MAILFILE
$CAT $MAILFILE | $MAILER -s "CPU Load is on ${HOSTNAME} is $CPU_LOAD %" $mailto
fi

This seems to be working properly for the sar and ps however I'm still getting alerts emailed for things like CPU Load is 3.18%. Unless I'm missing something it shouldn't trigger unless load is greater than 25%.

It seems though that it's more doing if load is greater than 2.5% Any suggestions?

Thank you

Cyrus
  • 84,225
  • 14
  • 89
  • 153

3 Answers3

1

Instead of using:

if [[ $CPU_LOAD > $LOAD ]];then

you must use

if [[ $CPU_LOAD -gt $LOAD ]]; then
0

Bash only handles integers, so to use higher precision, you could do something like this:

cpu_limit=25
# read the 5min load-average straight from the special file on /proc
read -r _ load_avg _ </proc/loadavg
# multiply by 100 for precision
load_avg=$(bc <<<"scale=0; $load_avg * 100 / 1")
# compare numbers with (( )) instead
if (( load_avg > cpu_limit )); then
   ...
fi
Olli K
  • 1,720
  • 1
  • 16
  • 17
0

Try this code - (Tested - working fine)

$ cat f.sh
HOSTNAME=$(hostname -s)
LOAD=25.00
MAILFILE=$HOME/a.txt
MAILER=/bin/mailx
mailto="vipinkumarr89@gmail.com"
CPU_LOAD=$(sar -P ALL 1 10 |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 -e "Please check processes on ${HOSTNAME} the value of cpu load is $CPU_LOAD%.
Highest process is: $PROC" > $MAILFILE
cat $MAILFILE | $MAILER -s "CPU Load is on ${HOSTNAME} is $CPU_LOAD %" $mailto
}
fi
VIPIN KUMAR
  • 3,019
  • 1
  • 23
  • 34
  • So I did try this and it seems to do the same thing. With LOAD=25.00 still received email for it below 25% Please check processes on the value of cpu load is 4.88%. Highest process is: 1.1 8499 java – Mandrake Diamante May 10 '17 at 20:13
  • After doing a bit more testing it seems like changing load to 2500 instead of 25.00 seems to be creating the alerts at 25% instead of 2.5% – Mandrake Diamante May 19 '17 at 15:35