Thursday, September 23, 2010

Shell script to monitor disk space

Motivation:
Space full caused db transaction hang issue last week, and this week it caused javax.jms.JMSException: No space left on device, herein ActiveMQ cannot write message to its queue. I decide to write a shell script to watch the disk space.

Steps:
  1. Google for similar script and info
  2. Write the shell script 
  3. Start sendmail for email alert
  4. Add script to cronjob for auto monitoring
Commands:
  1. /etc/init.d/sendmail => Usage: /etc/init.d/sendmail {start|stop|restart|condrestart|status}
  2. /etc/init.d/crond => Usage: /etc/init.d/crond {start|stop|status|reload|restart|condrestart}
Two options to add script to cronjob:
  1. crontab -e
  2. Put shell script to /etc/cron.* folder (cron.daily/   cron.hourly/  cron.monthly/ cron.weekly/)
Script:
# http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html
# set admin email for alert

ADMIN_EMAIL="admin@sample.com"
# set alert level
ALERT_LEVEL=90
# set log folder to get deleted
LOG_FOLDER=/opt/logs/*

df -HP | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  echo $output
  used=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
  partition=$(echo $output | awk '{ print $2 }' )
  if [ $used -ge $ALERT_LEVEL ]; then
    echo "Running out of space \"$partition ($used%)\" on $(hostname) as on $(date)" |
    mail -s "Alert: Running out of disk space - $used% used" $ADMIN_EMAIL
              echo "Purging log files ..."
              find $LOG_FOLDER -mtime +2 -exec rm -f {} \;
              echo "DONE"   

  fi
done

Why use df - HP?

linux01:root > df -H
Filesystem             Size   Used  Avail Use% Mounted on
/dev/sda2              8.0G   2.7G   5.0G  35% /
192.168.253.131:/u001/ReleaseArchive/
                       289G   203G    78G  73% /jdrive

linux01:root > df -H -t ext3
Filesystem             Size   Used  Avail Use% Mounted on
/dev/sda2              8.0G   2.7G   5.0G  35% /

linux01:root > df -HP
Filesystem             Size   Used  Avail Use% Mounted on
/dev/sda2              8.0G   2.7G   5.0G  35% /
192.168.253.131:/u001/ReleaseArchive/   289G   203G    78G  73% /jdrive

Reference:
http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html

No comments:

Post a Comment