Shell Script To Monit Swap Usage
Some time our system started to use more swap area even 100% of swap area and the system crashes. So for a System Admin it would be very helpful when they get informed if the system started to use more swap usage so that system admin can manage the server before crashing. So I wrote a shell script which will Alert by send mail if the system started to use more that 70% of swap area.
$ vim swap-usage.sh
#!/bin/sh
free -m | grep Swap | while read output;
do
swap=$(echo $output | awk '{print $2}' )
used=$(echo $output | awk '{ print $3 }' )
freed=$(echo $output | awk '{ print $4 }' )
echo "Swap : $swap"
echo "Used : $used"
echo "Free : $freed"
usep=`expr $used \* 100 / $swap`
echo $usep
if [ $usep -ge 70 ]; then
echo "Swap Usage Alert Total Swap: \"$swap\" Used: \"$used ($usep%)\" Free:
\"$freed\" on $(hostname) as on $(date)" |
mail -s "Alert: Swap Usage space $usep%" mail1@example.com,mail2@example.com
fi
done
This script will send mails to the specified mails, if the system started to use more than 70% of swap area. For continuously check the swap usage we need to set a cronjob for executing this script. So that the system should monit the swap usage by executing this script.
Edit the corntab file.
$ sudo crontab -e
Set the cronjob to to execute the script in every 15 Mints.
*/15 * * * * ~/scripts/swap-usage.sh
Restart the Cron
$ sudo /etc/init.d/cron restart
Posted by Shahid
2 responses to "Shell Script To Monit Swap Usage"
19:45 on November 3rd, 2009
Hi, very nice script.
I use it on all my servers now.
Thou I change from 70 to 20, because I prefer no swapping at all..
also, note that you should change the crontab file, so that the root user wont get so many emails, 1 email each 15 minutes. (96 emails per day)
Change to this:
*/15 * * * * ~/scripts/swap-usage.sh >/dev/null 2>&1
11:26 on January 4th, 2010
Hi fred,
Thanks for reading the post.
You are right swap usage 70% is much higher. 20% is reasonable.