Bash Script To Set Email Alert for Disk Storage Status

Set Email Alert for Disk Storage Status

Overview

In this article, I am going to provide you bash script which helps you to set an email alert for the disk when your storage is full. This script will keep alerting you when your disk reaches to a threshold level or value.

Condition use:

  • If threshold value 70 then send an email alert

This is complete automated script which will send you an email notification when above conditions are true.

Make sure you have a mail server configured on your server. if not then follow below link which helps you to configure a mail server.

Read : Steps To Install Postfix Server on Linux

#!/bin/bash

##Global vars
email_ids='sysadmin@script.com'
threshold=70 ##Use Threshold value as per requirement
MAIL=$(which mail)
subject="Disk status $( hostname )"
temp_file=/tmp/disk_status

##Function      : check_disk_space
##Description   : it will check all partitions and it will return # non-zero exist status if use >= threshold

check_disk_space(){
awk -v threshold=$threshold 'BEGIN{
status = 0
cmd = "LC_ALL=C df -Ph"
while( cmd | getline ) {
used=$5
if ( $1 != "Filesystem" && int(used) >= threshold ) {
printf "CRITICAL : Disk space alert (%s) :: [ Partition %s | mount point %s ]n",
used,$1, $NF > "/dev/stderr"
status = 1
}
}
exit status
}'
}

check_disk_space > $temp_file 2>&1

if [[ -s $temp_file ]]
then
$MAIL -s $subject $email_ids < $temp_file
fi

Permissions :

Once you save the script, provide executable permission to run the script.

$ chmod +x check_disk_status.sh

Scheduled Cron:

Now setup Cron job which will be executing in every 10 minutes. By using cron you will be able to monitor Disk space in every ten minutes. you can set cron according your requirement.

vim /etc/crod.d/script

*/10 * * * * root /bin/bash /opt/scripts/check_disk_status.sh

Save and close the file.

This is well-tested script and provide you data without using more memory on the server.

You can modify above script according to your requirement. If you still face any issues to setup this script then comments down below in comment box. Stay connected & subscribe with techthings.org for more such articles.

Latest Comments
  1. 78King February 7, 2017
  2. Antonio G March 1, 2017

Leave a Reply

Your email address will not be published. Required fields are marked *