Disk Space Monitor

From Foochal

Jump to: navigation, search


Contents

Script

Create a file by using the following command:

vi /usr/bin/checkDiskSpace.sh

Copy-paste the following:

#!/bin/sh
# Filesystem            Size  Used Avail Use% Mounted on
# /dev/hdb2              72G   37G   31G  54% /
# /dev/hdb1             100M   19M   76M  20% /boot
# none                  373M     0  373M   0% /dev/shm
# /dev/fd0              1.4M  3.5K  1.3M   1% /mnt/floppy
if [ "$#" -eq "0" ]
then
 echo "Usage: checkDiskSpace.sh <volume> <threshold space in M> <email to notify (optional)>"
 echo "Example: checkDiskSpace.sh /dev/hdb2 1000" || echo "Disk space on `hostname` is "
 exit -1
fi

volume=$1
threshold=$2
if [ "$#" -eq "3" ]
then
 email=$3
fi

echo "Checking $volume, threshold is $threshold..."
spaceUsed=`df -m | grep $volume | awk '{print $3}'`
echo "Space used is $[spaceUsed]M"
if [ "$spaceUsed" -gt "$threshold" ]
then
 message="Alert, disk space used crossed the threshold: $[spaceUsed]M used on $volume. Threshold is set at $[threshold]M"
 if [ "$email" != "" ]
 then
  echo $message
  echo $message | mail -s "Low Disk Space Left on `hostname`" $email
 else
  echo $message
 fi
 exit 1
else
 echo "Relax, plenty of space, $[spaceUsed]M."
 exit 0
fi

Example

Identify which volume you want to monitor by looking at the "Mounted on" field. Most of the users want to monitor the "main partition" which is a lot of times mounted on "/". In the above example the partition mounted on "/" is "/dev/hdb2". Supposed you wanted the "admin" to get notified if the disk space left of "/" in the above example is more than 5GB, your crontab would look the following:

0 0 * * * /usr/bin/checkDiskSpace.sh /dev/hdb2 5000

Personal tools