Poor-man’s disk usage monitoring

Here is a Bash script that will monitor the usage (in %) of all disks and send a notification by e-mail if it reaches the given limit.


#!/bin/bash
#
# Poor-man's disk usage monitoring
#
# Call this script as a cronjob for instance very 5 minutes. It will send an
# e-mail if one of the filesystems is filled to more than LIMIT (%) every
# MAIL_PERIOD seconds. An e-mail will also be sent once when the disk usage
# goes back below LIMIT.
#
# If you use Outlook as a client, set a fixed-width for "unformatted" e-mails in
# the options (File / Options / Mail / Stationary and fonts / At the bottom)

set -e

LIMIT="${LIMIT:-80}" # per cent
MAIL_PERIOD="${MAIL_PERIOD:-600}" # seconds
MAIL_TO=replace@me.invalid          # recipients, comma separated

# Timestamp files
MAIL_TS_FILE=/tmp/dfwarning-mail.ts
WARN_TS_FILE=/tmp/dfwarning-warn.ts

dfout=`df -h | awk -v "LIMIT=$LIMIT" '(NR >= 2 && $5 >= LIMIT) {print $0}'`
# echo $dfout

if [ "$dfout" ] ; then
# echo "Warning detected"
touch "$WARN_TS_FILE"
if [ ! -e "$MAIL_TS_FILE" -o "`find '$MAIL_TS_FILE' -mmin +$MAIL_PERIOD 2>/dev/null`" ] ; then
# echo "Sending mail"
( echo "Warning issued" ; echo "$dfout" ) | mailx -E -s "Disk usage on `hostname`: WARNING" "$MAIL_TO"
touch "$MAIL_TS_FILE"
fi
else
# echo "No warning"
if [ -e "$WARN_TS_FILE" ] ; then
( echo "Warning cleared" ; df -h ) | mailx -E -a 'Content-Type: text/plain' -s "Disk usage on `hostname`: OK" "$MAIL_TO"
fi
rm -f "$MAIL_TS_FILE" "$WARN_TS_FILE"
fi

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.