Shell Script to Monitor Disk Space Utilization and Send Email Alerts

In this article, we will explore how to monitor disk space utilization on Linux systems using Shell scripting and automate the process of sending email alerts when disk space crosses predefined thresholds. When disk space reaches critically low levels, it can lead to system crashes, data corruption, and other serious issues. Therefore, implementing a proactive approach to monitor disk space and receive alerts when thresholds are exceeded is essential for maintaining system reliability and availability. We will delve into the technical details of implementing this solution using simple yet powerful shell scripting techniques.

Prerequisites

  • AWS Account with Ubuntu 24.04 LTS EC2 Instance.
  • Basic knowledge of Shell scripting.

Step #1:Generate the App Password

First go to your Google account.

Shell Script to Monitor Disk Space Utilization and Send Email Alerts 1

Search for App Password in the search bar.

Shell Script to Monitor Disk Space Utilization and Send Email Alerts 2

Enter your google account password to verify it’s you.

Shell Script to Monitor Disk Space Utilization and Send Email Alerts 3

Now Enter the app name for which you wanted to get the app password like Diskspace alert

And click on Create to create it

Shell Script to Monitor Disk Space Utilization and Send Email Alerts 4

the password will be generated. Note it down cause will be using it.

Shell Script to Monitor Disk Space Utilization and Send Email Alerts 5

Step #2:Create a file in Ubuntu

Open the terminal and use the nano command to create a new file.

nano diskspace_alert.sh
Shell Script to Monitor Disk Space Utilization and Send Email Alerts 6

Step #3:Write a Script to Monitor Disk Space Utilization and Send Email Alerts

Below is a basic script to Monitor Disk Space Utilization and Send Email Alerts.

#!/bin/bash

# Function to check disk space
check_disk_space() {
    # Get available disk space in percentage
    disk_space=$(df -h / | awk 'NR==2 {print $5}' | cut -d'%' -f1)

    # Threshold for disk space utilization (adjust as needed)
    threshold=25

    # Check if disk space exceeds the threshold
    if [ "$disk_space" -ge "$threshold" ]; then
        return 1  # Disk space is critically low
    else
        return 0  # Disk space is normal
    fi
}

# Function to send email
send_email() {
    sender="[email protected]"  # Your email address
    receiver="[email protected]"  # Recipient's email address
    gapp="yqic unmr sydl nqfz"  # Your Google App password
    sub="Disk Space Alert"
    body="Disk space is critically low. Please take necessary action."

    # Sending email using curl
    response=$(curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
        --mail-from "$sender" \
        --mail-rcpt "$receiver" \
        --user "$sender:$gapp" \
        -T <(echo -e "From: $sender\nTo: $receiver\nSubject: $sub\n\n$body"))

    if [ $? -eq 0 ]; then
        echo "Email sent successfully."
    else
        echo "Failed to send email."
        echo "Response: $response"
    fi
}

# Main script
check_disk_space
if [ $? -eq 1 ]; then
    send_email
fi
Shell Script to Monitor Disk Space Utilization and Send Email Alerts 7

Save the file and exit the editor.

Explanation of the Script:

check_disk_space() Function:

  • This function checks the disk space utilization by using the df -h / command to get information about the root file system.
  • It extracts the percentage of disk space used from the output using awk and cut.
  • The threshold for disk space utilization is set to 25% (adjustable as needed).
  • If the disk space exceeds the threshold, the function returns 1 indicating that disk space is critically low. Otherwise, it returns 0 indicating that disk space is normal.

send_email() Function:

  • This function sends an email alert using Gmail’s SMTP server.
  • It defines variables for the sender’s email address (sender), recipient’s email address (receiver), and Google App password (gapp).
  • The subject of the email is set to “Disk Space Alert”, and the body contains the message “Disk space is critically low. Please take necessary action.”
  • The email is sent using curl with the provided parameters. The response from the server is captured in the response variable.
  • If the email is sent successfully, it prints “Email sent successfully.” Otherwise, it prints “Failed to send email.” along with the response from the server.

Main Script:

  • The check_disk_space function is called to determine if the disk space is critically low.
  • If the return value of check_disk_space is 1 (indicating critically low disk space), the send_email function is called to send an email alert.

Step #4:Make file executable

Change the file permissions to make it executable using the chmod command.

chmod +x diskspace_alert.sh
Shell Script to Monitor Disk Space Utilization and Send Email Alerts 8

Step #5:Run the script

Run the script by executing the following command.

./diskspace_alert.sh
Shell Script to Monitor Disk Space Utilization and Send Email Alerts 9

You will get the message Email sent successfully.

Now check the mail box to see if you receive the mail or not.

Shell Script to Monitor Disk Space Utilization and Send Email Alerts 10

As you can see the message we have written in script is displayed (Disk space is critically low. Please take necessary action.).

Conclusion:

In conclusion, monitoring disk space utilization and receiving timely alerts are essential components of proactive system administration. By harnessing the power of Shell scripting and leveraging built-in Linux utilities, we can create robust solutions to monitor disk space and ensuring system reliability. Automating email alerts adds an extra layer of proactive monitoring, enabling administrators to address potential issues promptly and minimize downtime. With the techniques outlined in this article, it makes easy to monitor disk space utilization and send email alerts for system administrators which can enhance the stability and performance of their systems while staying ahead of potential storage-related challenges.

Related Articles:

Shell Script to automate log rotation

Reference:

Bash reference manual

Prasad Hole

Leave a Comment

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

Share via
Copy link
Powered by Social Snap