Simple server load email notification script

Last week we had some trouble with high server load on some servers. I made some adjustments in the scripts and then needed to sit all day looking at the screen to monitor the server load (to see if my changes had any effect). Because it was great weather outside and it was weekend, I really did not feel like doing that. So I wrote a simple bash script that looks at the server load every 5 minutes and if the load would be higher than a threshold I chose, the script would mail me with the current load. So whenever I would receive an email, I would just wait 5 minutes and if another email came, I knew the load was too high for 10 minutes and I would only then log in to the server. If no second email came after 5 minutes, I knew the load was acceptable again.

Here is what I wrote (and saved as mail-load.sh):

#!/bin/bash
threshold=1.50
load=`cat /proc/loadavg | awk '{print $1}'`
response=`echo | awk -v T=$threshold-v L=$load 'BEGIN{if ( L > T){ print "highload"}}'`
if [ $response = "highload" ]
then
    echo -e 'Subject: High Load' $load'\nTo:[email protected]\nCc:[email protected]\n\nHigh Load:' $load | /usr/sbin/sendmail -t
fi

The number I define for threshold is the server load I find acceptable and for any load higher than that, I want to be notified. I am only interested in the 1 minute load, so the variable “load” is assigned to that value. And as you can see I also define a CC, so my colleague is also notified.
I set up a cron job to call this script every 5 minutes.

This is a very simple script and can be expanded in many ways. Like calculating the threshold based on how many CPU’s you have or put more info in the email, like the top 10 running processes, the last X lines of the error and access log and more. If you need a simple script, use the code above, otherwise you can read some of the following articles I found online about how to include more in the notification email:
http://www.bergspot.com/blog/2012/12/bash-script-to-check-server-load-and-notify-by-email/
http://www.cpanelkb.net/server-load-alerts-shell-script/
https://github.com/phillcoxon/loadwatch/blob/master/bin/loadwatch_ubuntu.sh

Oh, and…… I enjoyed my free day in the sun 🙂

You may also like...