Tuesday, December 7, 2010

Script for Cronjob to Check for a Full Disk

I found a nice script on the Ubuntu forums (I think) for checking if a Linux system had a full disk and then sending an email if that was the case. I adapted it a little bit to provide more information in the case that /home is full. I'm posting it here in case anyone were to find it useful.

#!/bin/bash
#set -x

TO_ADDR=email@address.com
THRESHOLD_PERCENT=85
OUTPUT_FILE=`/root/cron/tempfile`

df -H | awk '!/^Filesystem|tmpfs|cdrom|AFS/ { gsub(/\%/,"",$5); print $5,$1,$6}' | while read line
do
    eval $(echo "$line" | awk '{print "PERCENT_FULL="$1";DEVICE="$2";MOUNT_POINT="$3}')
    if [ $PERCENT_FULL -ge $THRESHOLD_PERCENT ]; then
        (
        echo -e "On $(hostname), the mount point $MOUNT_POINT is $PERCENT_FULL% full.\n"
        echo "df --human-readable shows:"
        df --human-readable $DEVICE
        if [ "$MOUNT_POINT" == "/home" ]; then
            du --one-file-system --summarize --human-readable ${MOUNT_POINT}/* > $OUTPUT_FILE
            echo -e "\nHere is the disk usage by directory listing, sorted from greatest to least."
            for directory in `du --one-file-system --summarize ${MOUNT_POINT}/*  | sort --reverse --numeric-sort --key=1 | awk '{print $2}'`
            do
                grep "$directory" --word-regexp $OUTPUT_FILE
            done
        fi
        ) | mailx -s "ALERT: $MOUNT_POINT on $(hostname) is $PERCENT_FULL% full" $TO_ADDR
    fi 
done
rm -f $OUTPUT_FILE