Monday, May 7, 2012

Script to Check Disk Space and Send Mail if its Full

The script below is done in Bash, which can be used across all Linux platforms. The function of the script is to check disk space at regular intervals and report back through e-mail if the server is running out of disk space. We can also specify multiple e-mail addresses.

1. Navigate to /root.
$ cd /root

2. Create a new file
$ vim diskcheck.sh
or
$ vi diskcheck.sh

3. Insert the following lines to the file
-----------------------------------
#!/bin/sh
df -HlP | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
 partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge 95 ]; then
echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
mail -s "Alert: Almost out of disk space $usep%" xyz@domain.com
echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
mail -s "Alert: Almost out of disk space $usep%" xyz1@domain.com
echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
mail -s "Alert: Almost out of disk space $usep%" xyz2@domain.com
fi
done
-----------------------------------

4.  Give execute permission.
$ chmod 755  diskcheck.sh

5. Set a cron to check it at regular intervals.
$ crontab -e
*/5 * * * * sh -x diskcheck.sh
(This will check every 5 minutes)

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews