Site icon https://inertz.org

How to Automate cPanel/WHM Server Monitoring with Bash Scripts

Picsum ID: 200

Article illustration

Managing a cPanel/WHM server requires constant vigilance. CPU spikes, disk exhaustion, and service failures can happen at any time — often when you’re least expecting them. In this guide, we’ll build a comprehensive Bash-based monitoring solution that keeps you informed before small issues become critical outages.

Why Automate Server Monitoring?

Manual checks are error-prone and unsustainable. A well-designed monitoring script runs continuously, logs anomalies, and sends alerts — giving you peace of time to focus on strategic work rather than firefighting.

Building the Core Monitoring Script

We’ll start with a foundation script that checks CPU load, memory usage, disk consumption, and critical services (httpd, mysql, exim, named):

#!/bin/bash
# /root/scripts/server-health-check.sh
THRESHOLD_CPU=80
THRESHOLD_MEM=85
THRESHOLD_DISK=90
ALERT_EMAIL="admin@inertz.org"

check_cpu() {
    local load=$(cat /proc/loadavg | awk '{print $1}')
    local cores=$(nproc)
    local pct=$(echo "$load $cores" | awk '{printf "%.0f", ($1/$2)*100}')
    if [ "$pct" -gt "$THRESHOLD_CPU" ]; then
        echo "HIGH CPU: ${pct}% load (${load} on ${cores} cores)"
    fi
}

check_disk() {
    df -h | awk 'NR>1 && int($5) > 90 {print "DISK WARNING: " $6 " at " $5}'
}

check_services() {
    for svc in httpd mysql exim named; do
        if ! systemctl is-active --quiet $svc; then
            echo "SERVICE DOWN: $svc"
        fi
    done
}

check_cpu
check_disk
check_services

Setting Up Cron-Based Execution

Schedule the script to run every 5 minutes via cron:

*/5 * * * * /root/scripts/server-health-check.sh >> /var/log/server-health.log 2>&1

Adding Email Alerts

Extend the script to send email alerts when thresholds are breached. Configure Exim or use a relay service like Mailgun for reliable delivery.

Conclusion

Automating server monitoring with Bash is straightforward and highly effective. Start with basic checks, then expand to include log analysis, SSL certificate expiry tracking, and automated backups. Your future self will thank you.

Exit mobile version