SlideShare a Scribd company logo
1 of 5
Download to read offline
Shell Script - Disk Usage Report and E-Mail Current Threshold Status
Overview
The purpose of this script is to send notification of current disk space utilization and also to monitor disk
usage every 12 hours and find out disk usage difference in usage from last 12 hours in bytes for each
partition.
The script will generate disk space usage report and send notification to the recipients.
This report will help administrators whether the report has to be shared with appropriate application
owners to clean up disk(s).
Also when the threshold limit or 90% and above is reached, disk partition usage % is shade in “RED”,
signifying that it’s a “Critical Alert”.
Applies To
 Tested on CentOS 7
Pre-requisites
Bash
Shell Script – Snippet
Copy and paste the script into a file, change script permission and run it.
#!/bin/bash
#
# To debug uncomment the below line
#set -x
#
# Set Environment Variables
#
TODAY="at $(date '+%H:%M on %d-%b-%y')"
OutputFilename=$(date +"%b_%d_%Y".html)
LastReport=/tmp/LastReport.txt
NowReport=/tmp/NowReport.txt
CurDate=`date +%D %T %Z`
#
# Set Alert Type according to Percentage
#
CriticalPercentage=90
WarningPercentage=80
NormalPercentage=70
Shell Script - Disk Usage Report and E-Mail Current Threshold Status
#
# Get IP Address set from hosts file
#
IPADDRESS=`head -n 1 /etc/hosts | awk ' { print $1 }'`
#
# Remove Output File, if it already exists
#
if [ -f /tmp/${OutputFilename} ]; then
rm -f /tmp/${OutputFilename}
fi
if [ -f ${NowReport} ]; then
mv ${NowReport} ${LastReport}
cp /dev/null ${NowReport}
fi
#
# Find out Difference Previous and Current Report for each partition
#
df -Pl | grep -vE "^Filesystem|tmpfs|cdrom" | awk 'NR>0 && NF==6' | awk '{print $3}' > ${NowReport}
if [ -f ${LastReport} ]; then
DiffValue=(`awk '{ getline getdifference < "/tmp/LastReport.txt"; $1 -= getdifference; print }'
/tmp/NowReport.txt`)
fi
#
# Defining HTML Table Format & Fields
#
(
echo '<HTML><HEAD><TITLE>Disk Usage Statistics</TITLE></HEAD>'
echo '<BODY>'
echo '<H3>Disk Usage Report for server - '$(uname -n) for ${IPADDRESS}'</H3>'
echo '<P>Report Generated '${TODAY}'</P>'
echo '<TABLE BORDER=3 CELLSPACING=2 CELLPADDING=0>'
echo '<TR BGCOLOR="#BBFFFF"> <TH>Filesystem</TH> <TH>Total</TH> <TH>Disk Used</TH>
<TH>Available</TH> <TH>Percentage Info</TH> <TH>Mounted On</TH> <TH>Critical Alert</TH>
<TH>Report Date</TH> <TH>12 Hrs Difference </TH><//TR>'
Shell Script - Disk Usage Report and E-Mail Current Threshold Status
#
# Extract Disk Usage Information
# Suppress Listing of “FileSystem, tmpfs and cdrom” Information
#
ArryCount=0
df -Pl | grep -vE "^Filesystem|tmpfs|cdrom" | awk 'NR>0 && NF==6'|sort|while read FileSystem Size
DiskUsed DiskFree DiskPercentUsed MountPoint
do
PERCENT=${DiskPercentUsed%%%}
#
# Calculate the Difference between previous run and current run
#
TDiffValue=(`awk '{ getline getdifference < "/tmp/LastReport.txt"; $1 -= getdifference; print }'
/tmp/NowReport.txt`)
#
# Verify if disk usage is greater equal to than set threshold limit - 90%
#
if [[ ${PERCENT} -ge ${CriticalPercentage} ]];
then
COLOR=red
CRITICALALERT="Yes, Notify"
elif [ ${PERCENT} -ge ${WarningPercentage} ] && [ ${PERCENT} -le 80 ];
then
COLOR=orange
CRITICALALERT=No
else
COLOR=green
CRITICALALERT=NA
fi
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>'$MountPoint'</TD>'
echo '<TD><FONT font-weight="bold">'$CRITICALALERT'</TD></FONT>'
echo '<TD><FONT font-weight="bold">'`date`'</TD></FONT>'
echo '<TD><FONT font-weight="bold">'${TDiffValue[ArryCount]} (in bytes)'</TD></FONT></TR>'
echo $DiskUsed >> `hostname`.usage.txt
Shell Script - Disk Usage Report and E-Mail Current Threshold Status
ArryCount=$ArryCount+1
done
echo '</TABLE>'
echo '</P><BR>'
echo '<TABLE BORDER=1 CELLSPACING=3 CELLPADDING=0>'
echo '<TR><TH FONT font-weight="bold">Legend Information</TH></TR>'
echo '<TR><TD FONT color="white" BGCOLOR="RED">Critical Alert</TD></TR>'
echo '<TR><TD FONT color="white" BGCOLOR="ORANGE">Warning Alert</TD></TR>'
echo '<TR><TD FONT color="white" BGCOLOR="GREEN">No Action Alert</TD></TR>'
echo '</TABLE>'
echo '<BODY></HTML>'
echo '<P><FONT font-weight="bold">Report Generated by IT Team</P>'
) | tee `hostname`_${0##*/}.html
#
# Sending E-Mail Notification
#
(
echo To: ToRecipient.Account@domainname.com
echo From: FromRecipient.Account@domainname.com
echo "Content-Type: text/html; "
echo Subject: Disk Usage Report for server `hostname` 'for' $IPADDRESS
echo
cat `hostname`_${0##*/}.html
) | sendmail -t
echo -e "Report Generation is Completed... na"
Run Disk Usage Report – Shell Script
To run the script, ensure you change the file permission to “executable” and then run it;
chmod +x ./DiskUsageReport.sh
./DiskUsageReport.sh
Shell Script - Disk Usage Report and E-Mail Current Threshold Status
Disk Usage E-Mail Report
A sample email report is shown below;

More Related Content

What's hot

Reitit - Clojure/North 2019
Reitit - Clojure/North 2019Reitit - Clojure/North 2019
Reitit - Clojure/North 2019Metosin Oy
 
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호KTH, 케이티하이텔
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulationborkweb
 
syzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzersyzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzerDmitry Vyukov
 
IPC in Microkernel Systems, Capabilities
IPC in Microkernel Systems, CapabilitiesIPC in Microkernel Systems, Capabilities
IPC in Microkernel Systems, CapabilitiesMartin Děcký
 
COSCUP2016 - LLVM框架、由淺入淺
COSCUP2016 - LLVM框架、由淺入淺COSCUP2016 - LLVM框架、由淺入淺
COSCUP2016 - LLVM框架、由淺入淺hydai
 
Gstreamer: an Overview
Gstreamer: an OverviewGstreamer: an Overview
Gstreamer: an OverviewRodrigo Costa
 
Linux Linux Traffic Control
Linux Linux Traffic ControlLinux Linux Traffic Control
Linux Linux Traffic ControlSUSE Labs Taipei
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
Prometheus on EKS
Prometheus on EKSPrometheus on EKS
Prometheus on EKSJo Hoon
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScriptpcnmtutorials
 
Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQICS
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent EventTencent
 
Creating CentOS Template For CloudStack
Creating CentOS Template For CloudStackCreating CentOS Template For CloudStack
Creating CentOS Template For CloudStackShanker Balan
 

What's hot (20)

Reitit - Clojure/North 2019
Reitit - Clojure/North 2019Reitit - Clojure/North 2019
Reitit - Clojure/North 2019
 
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
syzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzersyzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzer
 
IPC in Microkernel Systems, Capabilities
IPC in Microkernel Systems, CapabilitiesIPC in Microkernel Systems, Capabilities
IPC in Microkernel Systems, Capabilities
 
COSCUP2016 - LLVM框架、由淺入淺
COSCUP2016 - LLVM框架、由淺入淺COSCUP2016 - LLVM框架、由淺入淺
COSCUP2016 - LLVM框架、由淺入淺
 
Network Drivers
Network DriversNetwork Drivers
Network Drivers
 
Gstreamer: an Overview
Gstreamer: an OverviewGstreamer: an Overview
Gstreamer: an Overview
 
Linux Linux Traffic Control
Linux Linux Traffic ControlLinux Linux Traffic Control
Linux Linux Traffic Control
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Prometheus on EKS
Prometheus on EKSPrometheus on EKS
Prometheus on EKS
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Php
PhpPhp
Php
 
Linux programming - Getting self started
Linux programming - Getting self started Linux programming - Getting self started
Linux programming - Getting self started
 
Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQ
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Protocol Buffers
Protocol BuffersProtocol Buffers
Protocol Buffers
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
Creating CentOS Template For CloudStack
Creating CentOS Template For CloudStackCreating CentOS Template For CloudStack
Creating CentOS Template For CloudStack
 
Bootstrap 3
Bootstrap 3Bootstrap 3
Bootstrap 3
 

Similar to Shell Script Disk Usage Report and E-Mail Current Threshold Status

Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2Leandro Lima
 
Sydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plansSydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution planspaulguerin
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Learning Puppet basic thing
Learning Puppet basic thing Learning Puppet basic thing
Learning Puppet basic thing DaeHyung Lee
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
R57shell
R57shellR57shell
R57shellady36
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptFile Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptVCP Muthukrishna
 
Introduction to Template::Toolkit
Introduction to Template::ToolkitIntroduction to Template::Toolkit
Introduction to Template::Toolkitduncanmg
 
Zendcon 2007 Api Design
Zendcon 2007 Api DesignZendcon 2007 Api Design
Zendcon 2007 Api Designunodelostrece
 
Drush. Secrets come out.
Drush. Secrets come out.Drush. Secrets come out.
Drush. Secrets come out.Alex S
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptxrani marri
 
Interface de Voz con Rails
Interface de Voz con RailsInterface de Voz con Rails
Interface de Voz con RailsSvet Ivantchev
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingDan Morrill
 
Create an auto-extractible shell script linux
Create an auto-extractible shell script linuxCreate an auto-extractible shell script linux
Create an auto-extractible shell script linuxThierry Gayet
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12Tim Bunce
 

Similar to Shell Script Disk Usage Report and E-Mail Current Threshold Status (20)

serverstats
serverstatsserverstats
serverstats
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Sydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plansSydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plans
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Apache Velocity 1.6
Apache Velocity 1.6Apache Velocity 1.6
Apache Velocity 1.6
 
Learning Puppet basic thing
Learning Puppet basic thing Learning Puppet basic thing
Learning Puppet basic thing
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
R57shell
R57shellR57shell
R57shell
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptFile Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
 
Introduction to Template::Toolkit
Introduction to Template::ToolkitIntroduction to Template::Toolkit
Introduction to Template::Toolkit
 
Zendcon 2007 Api Design
Zendcon 2007 Api DesignZendcon 2007 Api Design
Zendcon 2007 Api Design
 
Drush. Secrets come out.
Drush. Secrets come out.Drush. Secrets come out.
Drush. Secrets come out.
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Interface de Voz con Rails
Interface de Voz con RailsInterface de Voz con Rails
Interface de Voz con Rails
 
Tt subtemplates-caching
Tt subtemplates-cachingTt subtemplates-caching
Tt subtemplates-caching
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
 
Create an auto-extractible shell script linux
Create an auto-extractible shell script linuxCreate an auto-extractible shell script linux
Create an auto-extractible shell script linux
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12
 

More from VCP Muthukrishna

How to Fix Duplicate Packages in YUM on CentOS 7
How to Fix Duplicate Packages in YUM on CentOS 7How to Fix Duplicate Packages in YUM on CentOS 7
How to Fix Duplicate Packages in YUM on CentOS 7VCP Muthukrishna
 
How To Install and Configure GNome on CentOS 7
How To Install and Configure GNome on CentOS 7How To Install and Configure GNome on CentOS 7
How To Install and Configure GNome on CentOS 7VCP Muthukrishna
 
How To Connect to Active Directory User Validation
How To Connect to Active Directory User ValidationHow To Connect to Active Directory User Validation
How To Connect to Active Directory User ValidationVCP Muthukrishna
 
How To Connect To Active Directory PowerShell
How To Connect To Active Directory PowerShellHow To Connect To Active Directory PowerShell
How To Connect To Active Directory PowerShellVCP Muthukrishna
 
How To List Files on Remote Server - PowerShell
How To List Files on Remote Server - PowerShellHow To List Files on Remote Server - PowerShell
How To List Files on Remote Server - PowerShellVCP Muthukrishna
 
How To List Files and Display In HTML Format
How To List Files and Display In HTML FormatHow To List Files and Display In HTML Format
How To List Files and Display In HTML FormatVCP Muthukrishna
 
How To Check and Delete a File via PowerShell
How To Check and Delete a File via PowerShellHow To Check and Delete a File via PowerShell
How To Check and Delete a File via PowerShellVCP Muthukrishna
 
Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...
Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...
Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...VCP Muthukrishna
 
How To Setup SSH Keys on CentOS 7
How To Setup SSH Keys on CentOS 7How To Setup SSH Keys on CentOS 7
How To Setup SSH Keys on CentOS 7VCP Muthukrishna
 
How To Install and Configure Open SSH Server on Ubuntu
How To Install and Configure Open SSH Server on UbuntuHow To Install and Configure Open SSH Server on Ubuntu
How To Install and Configure Open SSH Server on UbuntuVCP Muthukrishna
 
Windows PowerShell Basics - How To List PSDrive Info
Windows PowerShell Basics - How To List PSDrive InfoWindows PowerShell Basics - How To List PSDrive Info
Windows PowerShell Basics - How To List PSDrive InfoVCP Muthukrishna
 
How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7VCP Muthukrishna
 
Windows PowerShell Basics – How To Create powershell for loop
Windows PowerShell Basics – How To Create powershell for loopWindows PowerShell Basics – How To Create powershell for loop
Windows PowerShell Basics – How To Create powershell for loopVCP Muthukrishna
 
How To Construct IF and Else Conditional Statements
How To Construct IF and Else Conditional StatementsHow To Construct IF and Else Conditional Statements
How To Construct IF and Else Conditional StatementsVCP Muthukrishna
 
How To Create PowerShell Function Mandatory Parameter and Optional Parameter
How To Create PowerShell Function Mandatory Parameter and Optional ParameterHow To Create PowerShell Function Mandatory Parameter and Optional Parameter
How To Create PowerShell Function Mandatory Parameter and Optional ParameterVCP Muthukrishna
 
How To Create Power Shell Function Mandatory Parameter Value
How To Create Power Shell Function Mandatory Parameter ValueHow To Create Power Shell Function Mandatory Parameter Value
How To Create Power Shell Function Mandatory Parameter ValueVCP Muthukrishna
 
How To Create PowerShell Function
How To Create PowerShell FunctionHow To Create PowerShell Function
How To Create PowerShell FunctionVCP Muthukrishna
 
How To Disable IE Enhanced Security Windows PowerShell
How To Disable IE Enhanced Security Windows PowerShellHow To Disable IE Enhanced Security Windows PowerShell
How To Disable IE Enhanced Security Windows PowerShellVCP Muthukrishna
 
How To Check IE Enhanced Security Is Enabled Windows PowerShell
How To Check IE Enhanced Security Is Enabled Windows PowerShellHow To Check IE Enhanced Security Is Enabled Windows PowerShell
How To Check IE Enhanced Security Is Enabled Windows PowerShellVCP Muthukrishna
 
How To Configure Nginx Load Balancer on CentOS 7
How To Configure Nginx Load Balancer on CentOS 7How To Configure Nginx Load Balancer on CentOS 7
How To Configure Nginx Load Balancer on CentOS 7VCP Muthukrishna
 

More from VCP Muthukrishna (20)

How to Fix Duplicate Packages in YUM on CentOS 7
How to Fix Duplicate Packages in YUM on CentOS 7How to Fix Duplicate Packages in YUM on CentOS 7
How to Fix Duplicate Packages in YUM on CentOS 7
 
How To Install and Configure GNome on CentOS 7
How To Install and Configure GNome on CentOS 7How To Install and Configure GNome on CentOS 7
How To Install and Configure GNome on CentOS 7
 
How To Connect to Active Directory User Validation
How To Connect to Active Directory User ValidationHow To Connect to Active Directory User Validation
How To Connect to Active Directory User Validation
 
How To Connect To Active Directory PowerShell
How To Connect To Active Directory PowerShellHow To Connect To Active Directory PowerShell
How To Connect To Active Directory PowerShell
 
How To List Files on Remote Server - PowerShell
How To List Files on Remote Server - PowerShellHow To List Files on Remote Server - PowerShell
How To List Files on Remote Server - PowerShell
 
How To List Files and Display In HTML Format
How To List Files and Display In HTML FormatHow To List Files and Display In HTML Format
How To List Files and Display In HTML Format
 
How To Check and Delete a File via PowerShell
How To Check and Delete a File via PowerShellHow To Check and Delete a File via PowerShell
How To Check and Delete a File via PowerShell
 
Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...
Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...
Zimbra Troubleshooting - Mails not being Delivered or Deferred or Connection ...
 
How To Setup SSH Keys on CentOS 7
How To Setup SSH Keys on CentOS 7How To Setup SSH Keys on CentOS 7
How To Setup SSH Keys on CentOS 7
 
How To Install and Configure Open SSH Server on Ubuntu
How To Install and Configure Open SSH Server on UbuntuHow To Install and Configure Open SSH Server on Ubuntu
How To Install and Configure Open SSH Server on Ubuntu
 
Windows PowerShell Basics - How To List PSDrive Info
Windows PowerShell Basics - How To List PSDrive InfoWindows PowerShell Basics - How To List PSDrive Info
Windows PowerShell Basics - How To List PSDrive Info
 
How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7
 
Windows PowerShell Basics – How To Create powershell for loop
Windows PowerShell Basics – How To Create powershell for loopWindows PowerShell Basics – How To Create powershell for loop
Windows PowerShell Basics – How To Create powershell for loop
 
How To Construct IF and Else Conditional Statements
How To Construct IF and Else Conditional StatementsHow To Construct IF and Else Conditional Statements
How To Construct IF and Else Conditional Statements
 
How To Create PowerShell Function Mandatory Parameter and Optional Parameter
How To Create PowerShell Function Mandatory Parameter and Optional ParameterHow To Create PowerShell Function Mandatory Parameter and Optional Parameter
How To Create PowerShell Function Mandatory Parameter and Optional Parameter
 
How To Create Power Shell Function Mandatory Parameter Value
How To Create Power Shell Function Mandatory Parameter ValueHow To Create Power Shell Function Mandatory Parameter Value
How To Create Power Shell Function Mandatory Parameter Value
 
How To Create PowerShell Function
How To Create PowerShell FunctionHow To Create PowerShell Function
How To Create PowerShell Function
 
How To Disable IE Enhanced Security Windows PowerShell
How To Disable IE Enhanced Security Windows PowerShellHow To Disable IE Enhanced Security Windows PowerShell
How To Disable IE Enhanced Security Windows PowerShell
 
How To Check IE Enhanced Security Is Enabled Windows PowerShell
How To Check IE Enhanced Security Is Enabled Windows PowerShellHow To Check IE Enhanced Security Is Enabled Windows PowerShell
How To Check IE Enhanced Security Is Enabled Windows PowerShell
 
How To Configure Nginx Load Balancer on CentOS 7
How To Configure Nginx Load Balancer on CentOS 7How To Configure Nginx Load Balancer on CentOS 7
How To Configure Nginx Load Balancer on CentOS 7
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

Shell Script Disk Usage Report and E-Mail Current Threshold Status

  • 1. Shell Script - Disk Usage Report and E-Mail Current Threshold Status Overview The purpose of this script is to send notification of current disk space utilization and also to monitor disk usage every 12 hours and find out disk usage difference in usage from last 12 hours in bytes for each partition. The script will generate disk space usage report and send notification to the recipients. This report will help administrators whether the report has to be shared with appropriate application owners to clean up disk(s). Also when the threshold limit or 90% and above is reached, disk partition usage % is shade in “RED”, signifying that it’s a “Critical Alert”. Applies To  Tested on CentOS 7 Pre-requisites Bash Shell Script – Snippet Copy and paste the script into a file, change script permission and run it. #!/bin/bash # # To debug uncomment the below line #set -x # # Set Environment Variables # TODAY="at $(date '+%H:%M on %d-%b-%y')" OutputFilename=$(date +"%b_%d_%Y".html) LastReport=/tmp/LastReport.txt NowReport=/tmp/NowReport.txt CurDate=`date +%D %T %Z` # # Set Alert Type according to Percentage # CriticalPercentage=90 WarningPercentage=80 NormalPercentage=70
  • 2. Shell Script - Disk Usage Report and E-Mail Current Threshold Status # # Get IP Address set from hosts file # IPADDRESS=`head -n 1 /etc/hosts | awk ' { print $1 }'` # # Remove Output File, if it already exists # if [ -f /tmp/${OutputFilename} ]; then rm -f /tmp/${OutputFilename} fi if [ -f ${NowReport} ]; then mv ${NowReport} ${LastReport} cp /dev/null ${NowReport} fi # # Find out Difference Previous and Current Report for each partition # df -Pl | grep -vE "^Filesystem|tmpfs|cdrom" | awk 'NR>0 && NF==6' | awk '{print $3}' > ${NowReport} if [ -f ${LastReport} ]; then DiffValue=(`awk '{ getline getdifference < "/tmp/LastReport.txt"; $1 -= getdifference; print }' /tmp/NowReport.txt`) fi # # Defining HTML Table Format & Fields # ( echo '<HTML><HEAD><TITLE>Disk Usage Statistics</TITLE></HEAD>' echo '<BODY>' echo '<H3>Disk Usage Report for server - '$(uname -n) for ${IPADDRESS}'</H3>' echo '<P>Report Generated '${TODAY}'</P>' echo '<TABLE BORDER=3 CELLSPACING=2 CELLPADDING=0>' echo '<TR BGCOLOR="#BBFFFF"> <TH>Filesystem</TH> <TH>Total</TH> <TH>Disk Used</TH> <TH>Available</TH> <TH>Percentage Info</TH> <TH>Mounted On</TH> <TH>Critical Alert</TH> <TH>Report Date</TH> <TH>12 Hrs Difference </TH><//TR>'
  • 3. Shell Script - Disk Usage Report and E-Mail Current Threshold Status # # Extract Disk Usage Information # Suppress Listing of “FileSystem, tmpfs and cdrom” Information # ArryCount=0 df -Pl | grep -vE "^Filesystem|tmpfs|cdrom" | awk 'NR>0 && NF==6'|sort|while read FileSystem Size DiskUsed DiskFree DiskPercentUsed MountPoint do PERCENT=${DiskPercentUsed%%%} # # Calculate the Difference between previous run and current run # TDiffValue=(`awk '{ getline getdifference < "/tmp/LastReport.txt"; $1 -= getdifference; print }' /tmp/NowReport.txt`) # # Verify if disk usage is greater equal to than set threshold limit - 90% # if [[ ${PERCENT} -ge ${CriticalPercentage} ]]; then COLOR=red CRITICALALERT="Yes, Notify" elif [ ${PERCENT} -ge ${WarningPercentage} ] && [ ${PERCENT} -le 80 ]; then COLOR=orange CRITICALALERT=No else COLOR=green CRITICALALERT=NA fi 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>'$MountPoint'</TD>' echo '<TD><FONT font-weight="bold">'$CRITICALALERT'</TD></FONT>' echo '<TD><FONT font-weight="bold">'`date`'</TD></FONT>' echo '<TD><FONT font-weight="bold">'${TDiffValue[ArryCount]} (in bytes)'</TD></FONT></TR>' echo $DiskUsed >> `hostname`.usage.txt
  • 4. Shell Script - Disk Usage Report and E-Mail Current Threshold Status ArryCount=$ArryCount+1 done echo '</TABLE>' echo '</P><BR>' echo '<TABLE BORDER=1 CELLSPACING=3 CELLPADDING=0>' echo '<TR><TH FONT font-weight="bold">Legend Information</TH></TR>' echo '<TR><TD FONT color="white" BGCOLOR="RED">Critical Alert</TD></TR>' echo '<TR><TD FONT color="white" BGCOLOR="ORANGE">Warning Alert</TD></TR>' echo '<TR><TD FONT color="white" BGCOLOR="GREEN">No Action Alert</TD></TR>' echo '</TABLE>' echo '<BODY></HTML>' echo '<P><FONT font-weight="bold">Report Generated by IT Team</P>' ) | tee `hostname`_${0##*/}.html # # Sending E-Mail Notification # ( echo To: ToRecipient.Account@domainname.com echo From: FromRecipient.Account@domainname.com echo "Content-Type: text/html; " echo Subject: Disk Usage Report for server `hostname` 'for' $IPADDRESS echo cat `hostname`_${0##*/}.html ) | sendmail -t echo -e "Report Generation is Completed... na" Run Disk Usage Report – Shell Script To run the script, ensure you change the file permission to “executable” and then run it; chmod +x ./DiskUsageReport.sh ./DiskUsageReport.sh
  • 5. Shell Script - Disk Usage Report and E-Mail Current Threshold Status Disk Usage E-Mail Report A sample email report is shown below;