Tuesday 12 March 2013

monitorCpuUsage.sh


#monitorCpuUsage.sh

#!/bin/bash
usageHelp="Usage: ${0##*/}"
uidHelp="-u starting uid, must be an integer greater than or equal to 0 (only used with \"-w users\")"
maxCpuHelp="-m max cpu, must be an integer greater than or equal to 0 and less than 100"
watchHelp="-w what to watch, must be \"users\" or \"procs\""
emailHelp="-e must contain an email address"
debugHelp="-d specifies debug mode in which -e, -m, and -u do not need to be specified."
badOptionHelp="Option not recognised"
printHelpAndExit()
{
echo "$usageHelp"
echo "$uidHelp"
echo "$maxCpuHelp"
echo "$watchHelp"
echo "$emailHelp"
echo "$debugHelp"
exit $1
}
printErrorHelpAndExit()
{
        echo
        echo "$@"
        echo
        echo
        printHelpAndExit 1
}
whatTowatch=""
email=""
startAtUid="-1"
maxCpuUsage="-1"
debug=""
while getopts "hw:e:u:m:d" optionName; do
case "$optionName" in
h) printHelpAndExit 0;;
d) debug="0";;
w) whatTowatch="$OPTARG";;
e) email="$OPTARG";;
u) startAtUid="$OPTARG";;
m) maxCpuUsage="$OPTARG";;
[?]) printErrorHelpAndExit "$badOptionHelp";;
esac
done
outputCmd="mail -s 'CPU Abusers on ${HOSTNAME}' $email"
[[ "$whatTowatch" != "users" ]] && [[ "$whatTowatch" != "procs" ]] && printErrorHelpAndExit "$watchHelp"
if [[ -z "$debug" ]]
then
( [[ "$maxCpuUsage" -ge 0 ]] && [[ "$maxCpuUsage" -le 100 ]] ) || printErrorHelpAndExit "$maxCpuHelp"
[[ "$startAtUid" -eq -1 ]] && [[ "$whatTowatch" == "users" ]] && printErrorHelpAndExit "$uidHelp"
[[ -z "$email" ]] && printErrorHelpAndExit "$emailHelp"
else
outputCmd=cat
fi
tmpOutputFile=$( mktemp -q -t tmp.cpu.XXXXXXXXXXXX 2>/dev/null )
if [[ -z "$tmpOutputFile" ]] || [[ ! -f "$tmpOutputFile" ]]
then
        tmpOutputFile="/tmp/tmp.cpu.$(date +%S).$$"
        I=0
        while [[ -f "$tmpOutputFile" ]]
        do
                tmpOutputFile="$tmpOutputFile.$I"
                ((I++))
        done
fi
trap "rm -f $tmpOutputFile; exit" SIGINT SIGTERM
usersToWatch()
{
awk -F: '{print $1 , $3}' /etc/passwd | \
while read user id
do
if [ $id -ge $startAtUid ]
then
echo $user
fi
done
}
sum()
{
local cum=0
for i in $@
do
(( cum = cum + ${i%.*} ))
done
echo $cum
}
abusersExist()
{
if [[ "$whatTowatch" == "users" ]]
then
for user in $( usersToWatch )
do
cpu=$( ps -o pcpu -u $user | grep -v CPU )
local cumUsage=$( sum $cpu )
if [[ $cumUsage -ge $maxCpuUsage ]]
then
echo "User $user is using $cumUsage% cpu." >> $tmpOutputFile
fi
done
elif [[ "$whatTowatch" == "procs" ]]
then
local last=""
local cumUsage=0
ps -o comm,pcpu -e | grep -v CPU | sort | \
while read comm cpu
do
if [[ "$comm" != "$last" ]] && [[ ! -z "$last" ]]
then
if [[ $cumUsage -ge $maxCpuUsage ]]
then
echo "Process $last is using $cumUsage% cpu." >> $tmpOutputFile
fi
cumUsage=0
fi
cumUsage=$( sum $cumUsage $cpu )
last="$comm"
done
fi
}
abusersExist
if [ -s $tmpOutputFile ]
then
( date; cat $tmpOutputFile ) | eval "$outputCmd"
fi
rm -f $tmpOutputFile

No comments:

Post a Comment