Cpu and memory usage scripts

All

I am writing a script to generate an email when cpu and memory usage is high for 5 min continuously

help me urgent

I wrote below scritpt

LOAD=75.00
CPU_LOAD= 'sar -P all 300 5 |grep 'Average.all* '| awk -F " " '(print 100.0 -$NF)''
IF [{ $CPU_LOAD > $LOAD ]};
ECHO "pLEASE CHECK YOUR PROCESS ON YOUR $HOSTANME VALUE OF CPU ..." -S MAILX...

Is this best way to get 5 min output ?

also how to write for alerting high memory usage being high above75% for 5 min

You could run the check from cron every minute and keep a count of the number of times the CPU is high in a dat file then you can warn via email if the CPU is high for more than x checks and also notify when it normalises again.

I run something like this myself:

#!/bin/bash
CHKFILE=/usr/wrk/CPU.dat
LIMIT=25
CMAX=5
USAGE=$(sar 5 6 | grep "Average")
IDLE=$(echo $USAGE | awk '{printf "%.0d", $8}')

# Read in number of past checks that have exceeded $LIMIT
[ -f $CHKFILE ] && read CPUCNT < $CHKFILE
CPUCNT=${CPUCNT:-0}

[ -z "$IDLE" ] && exit

if (( IDLE < LIMIT ))
then
   ((CPUCNT++))
   ((CPUCNT >= CMAX)) &&
   mailx -s "Sustained high CPU usage: $((100 - IDLE))%" anil@domain.com <<EOF
$(echo $USAGE | awk '{printf "User: %s%%, Nice: %s%%, System: %s%%, I/O Wait: %s%% Steal %s%%\n", $3, $4, $5, $6,$7,$8}')
EOF
else
   ((CPUCNT >= CMAX)) &&
   mailx -s "CPU usage normalised: $((100 - IDLE))%" anil@domain.com <<EOF
$(echo $USAGE | awk '{printf "User: %s%%, Nice: %s%%, System: %s%%, I/O Wait: %s%% Steal %s%%\n", $3, $4, $5, $6,$7,$8}')
   CPUCNT=0
EOF
fi

echo "$CPUCNT" > $CHKFILE

Edit:
In a similar way you can use sar -r 5 6 (5 readings averaged over 6 seconds each) to monitor memory usage - Look at column #4 for pct memory used.
The counts for number of readings exceeding limit could be stored in the same data file.