Automating Server Maintenance with Shell Scripts

Disk Space Monitoring and Email Alerting

To maintain system stability, its crucial to monitor disk capacity. The following script checks the available space on the root (/) and boot (/boot) partitions. If the combined free space drops below 20GB, an alert email is dispatched to the system administrator.

Prerequisites

Ensure the mail transport agent is installed and active on the server.

sudo yum install postfix -y
sudo systemctl enable --now postfix

Monitoring Script

This script calculates free space in megabytes, sums the values, and converts them to gigabytes for comparison.

#!/bin/bash
# File Name: disk_monitor.sh
# Description: Monitors disk space and sends email alerts if space is low.

ALERT_EMAIL="admin@localhost"
THRESHOLD_GB=20

# Retrieve available space in MB for specific partitions
boot_avail=$(df -m /boot | tail -1 | awk '{print $4}')
root_avail=$(df -m / | tail -1 | awk '{print $4}')

# Calculate total free space in GB
total_free_mb=$((boot_avail + root_avail))
total_free_gb=$((total_free_mb / 1024))

# Check threshold and send alert
if [ "$total_free_gb" -lt "$THRESHOLD_GB" ]; then
    echo "Warning: Total free space is ${total_free_gb}GB, which is below the ${THRESHOLD_GB}GB limit." | mail -s "Disk Space Critical" "$ALERT_EMAIL"
fi

Scheduling the Task

Configure a cron job to execute this script daily at midnight.

0 0 * * * root /root/disk_monitor.sh

Web Service Management

This section demonstrates how to verify if the Apache HTTP service (httpd) is active. The script uses process identification to determine the service status. If the service is not detected, it attempts to start the service and temporarily disable the firewall to ensure connectivity.

Service Control Script

#!/bin/bash
# File Name: web_service.sh
# Description: Checks for httpd process and starts it if necessary.

# Check if the httpd process is running using pgrep
if pgrep -x httpd > /dev/null; then
    echo "The web server is currently running."
else
    echo "Web server stopped. Initializing start sequence..."
    systemctl start httpd
    systemctl stop firewalld
fi

HTTP Connectivity Verification

The final script uses curl to verify that the web server is responding to requests. If the connection is successful, it returns a confirmation message; otherwise, the script exits with a status code of 12 to indicate a failure.

Connectivity Script

#!/bin/bash
# File Name: check_web_status.sh
# Description: Tests HTTP connectivity and returns specific status codes.

TARGET_IP="192.168.1.100" # Replace with your server IP

# Perform a silent curl request
curl -s "$TARGET_IP" > /dev/null

if [ $? -eq 0 ]; then
    echo "web server is running"
else
    exit 12
fi

Posted on Thu, 25 Jun 2026 17:37:35 +0000 by AndreGuatemala