BASH
Monitor Server Disk Space and Send Email Alerts
Implement a bash script to monitor server disk space usage, automatically sending an email alert when a predefined threshold is exceeded, preventing potential outages.
#!/bin/bash
# --- Configuration ---
THRESHOLD=85 # Percentage (e.g., 85% full)
EMAIL_RECIPIENT="[email protected]"
SERVER_NAME="My Web Server"
# --- Script Logic ---
# Get disk usage for the root partition, excluding snap/loop/tmpfs
# Adjust 'grep -E' pattern if your root partition has a different name
# or you want to monitor specific partitions.
USAGE=$(df -h | grep -E '^/dev/vda1|^/dev/sda[0-9]|^/dev/mapper/' | awk '{ print $5 }' | sed 's/%//g')
# Check if USAGE is empty (no disk found or error)
if [ -z "$USAGE" ]; then
echo "[$(date)] Error: Could not retrieve disk usage. Exiting."
exit 1
fi
# Convert USAGE to integer
USAGE_INT=$(echo $USAGE | cut -d'.' -f1)
echo "[$(date)] Current disk usage is $USAGE% on $SERVER_NAME."
if [ "$USAGE_INT" -ge "$THRESHOLD" ]; then
SUBJECT="ALERT: High Disk Usage on $SERVER_NAME ($USAGE%)"
BODY="Disk usage on $SERVER_NAME has reached $USAGE%, which is above the threshold of $THRESHOLD%.
Please investigate immediately.
Detailed usage:
$(df -h)"
echo "[$(date)] Sending email alert to $EMAIL_RECIPIENT..."
# Make sure 'mail' or 'sendmail' is installed on your system
# e.g., sudo apt-get install mailutils (Debian/Ubuntu)
# e.g., sudo yum install mailx (CentOS/RHEL)
echo -e "$BODY" | mail -s "$SUBJECT" "$EMAIL_RECIPIENT"
if [ $? -eq 0 ]; then
echo "[$(date)] Email alert sent successfully."
else
echo "[$(date)] Failed to send email alert!"
fi
else
echo "[$(date)] Disk usage is within acceptable limits."
fi
echo "[$(date)] Disk monitoring script finished."
How it works: This script monitors the disk space usage of your server. It retrieves the percentage of used space for the root partition (or specified partitions) and compares it against a predefined `THRESHOLD`. If the usage exceeds this threshold, it composes an email with detailed information and sends it to the specified recipient. This helps in proactively identifying and addressing disk space issues before they impact server operations. Ensure you have a mail agent (like `mailx` or `mailutils`) installed and configured on your server.