Sunday 9 October 2011

Checking disk space on a UNIX / Linux machine

I have been looking for an all in one script that I can use to check on disk space on a UNIX / Linux machine, and if it past a certain percentage, email out a message to an email address informing about the result. I searched the web, and found a page called "Monitor UNIX / Linux Server Disk Space with Shell Script".

The code from that page looked good, but did not work properly on the Solaris machine I was trying it on - possibly due to some weird configurations in the command line shell. I made some modifications to the script, and hopefully have made it generically enough so it can be run on any UNIX / Linux system. The code is:

#!/usr/bin/sh
############################################################
# disk_test.sh
############################################################
# http://riconthego.blogspot.com/
############################################################
# This script is check disk space on a machine, and email
# out to a list
of people if any file systems are on 90+% ############################################################
df -k|awk '{ print $5 " " $6 }' | while read output; do
  usedPercentage=`echo $output | awk '{ print $1}' | cut -d'%' -f1 `

  driveMount=`echo $output | awk '{ print $2 }' `

  if [ $usedPercentage -gt 89 ]; then

    echo "Running out of disk space \"$driveMount ($usedPercentage%)\" on `hostname` as of `date`" | mailx -s "Alert: Partition on `hostname` is at $usedPercentage%" someone@somewhere.com

  fi

done


In the script, change the someone@somewhere.com argument passed into the mailx command to the email address that is the recipient of the information. Copy and paste the above code into a file called disk_test.sh, and then in the directory you saved the file in, type in the following command (without the "$" at the start):

$ chmod u+x disk_test.sh

This will change the permissions of the file allowing it to be executed as a script. Execute the script by typing the following command:

$ ./disk_test.sh

If everything has worked, you should not see any returned strings or characters to the console. If any of the partitions on the system meet the criteria in the test, a separate email should be sent for each mount that exceeds the threshold. Lastly, you should set up a periodic cron job, to automatically run the job on the filesystem. Depending on your requirements, you may want to run this script anywhere from once a week to once an hour.

No comments:

Post a Comment