Tuesday, November 3, 2015

Bash Script Disk Usage Report and E-Mail

Overview

The purpose of this document is to generate HTML Disk usage report and email the report.

Applies To

CentOS 7, RHEL 7

Pre-requisites

·        Bash

Shell Script Snippet

#!/bin/bash
#
# Environment Variables
#
TODAY="at $(date '+%H:%M on %d-%b-%y')"
OutputFilename=$(date +"%b_%d_%Y".html)

#
# Remove old HTML File
#
if [ -f /tmp/${OutputFilename} ]; then
               rm -f /tmp/${OutputFilename}
fi

#
# Create HTML File with Table
#
(
  echo '<HTML><HEAD><TITLE>Disk Usage Statistics</TITLE></HEAD>'
  echo '<BODY>'
  echo '<H3>Disk Usage Report for server - '$(uname -n)'</H3>'
  echo '<P>Report Generated '${TODAY}'</P>'
  echo '<TABLE BORDER=3 CELLSPACING=2 CELLPADDING=0>'
  echo '<TR BGCOLOR=\"#5CE6E6\"> <TH>Filesystem</TH> <TH>1024 blocks (Total)</TH> <TH>Disk Used</TH> <TH>Available</TH> <TH>Percentage Info</TH> <TH>Mounted On</TH> <TH>Critical Alert</TH></TR>'



#
# Collate Disk Usage Information
#
  df -Pml |awk 'NR>1 && NF==6'|sort|while read FileSystem Size DiskUsed DiskFree DiskPercentUsed MountPoint
  do
    PERCENT=${DiskPercentUsed%%%}
#
# Verify if disk usage is greater equal to, than set threshold limit - 90%
#
  if [[ ${PERCENT} -ge 90 ]];
    then
         COLOR=red
         CRITICALALERT="Yes, Notify"
#
# If the disk space used is greater than 70% and less than 80% set alert color as orange
#
    elif [ ${PERCENT} -ge 70 ] && [ ${PERCENT} -le 80 ];
    then
         COLOR=orange
         CRITICALALERT="No"
#
# Other usage percentage set color as green
#
    else
         COLOR=green
         CRITICALALERT="NA"
    fi
#
# Create Table Columns
#
    echo '<TR><TD>'$FileSystem'</TD><TD ALIGN=RIGHT>'$Size'</TD>'
    echo '<TD ALIGN=RIGHT>'$DiskUsed'</TD><TD ALIGN=RIGHT>'$DiskFree'</TD>'
    echo '<TD><TABLE BORDER=0 CELLSPACING=3 CELLPADDING=0>'
    echo '<TR><TD WIDTH='$((2 * $PERCENT))' BGCOLOR="'$COLOR'"></TD>'
    echo '<TD WIDTH='$((2 * (100 - $PERCENT)))' BGCOLOR="gray"></TD>'
    echo '<TD><FONT FONT-WEIGHT="bold" SIZE=-1 COLOR="'$COLOR'">'$DiskPercentUsed'</FONT></TD>'
    echo '<TR></TABLE></TD><TD>'$MountPoint'</TD>'
    echo '<TD><FONT font-weight="bold">'$CRITICALALERT'</TD></FONT></TR>'
  done
    echo '</TABLE><P><FONT font-weight="bold">By IT Team</P><BODY></HTML>'
) |  tee ${0##*/}.html


#
# Send E-Mail Notification – Snippet
#
(
  echo From: SendersEMailAddress@domain.com
  echo To: ReceiptsEMailAddress@domain.com
  echo "Content-Type: text/html; "
  echo Subject: Disk Usage Report for server `hostname`
  echo
  cat  ${0##*/}.html
) | sendmail -t

SlideShare Information


No comments:

Post a Comment