MathanKumar Stalin

Solution Engineer

System Engineer

DevOps Engineer

Ethical Hacker

Cyber Security

MathanKumar Stalin

Solution Engineer

System Engineer

DevOps Engineer

Ethical Hacker

Cyber Security

Blog Post

Simple Shell Script to Monitor CPU & RAM with Email Alerts (Clear & Critical)

We all face this issue—suddenly the server becomes slow, the website is loading like a tortoise, and we don’t know why. By the time we login and check top command, the server might hang or the issue might be gone.

Today I will share a super useful Shell Script. It acts like a CCTV camera for your server.

What this script does:

  1. It checks your CPU and Memory (RAM) usage every 5 minutes.
  2. Logic is simple:
    • > 80% usage: It marks as WARNING.
    • > 90% usage: It marks as CRITICAL.
    • < 80% usage: It marks as OK (Cleared).
  3. Smart Alerts: It sends an email only when the status changes.
    • If it goes High -> You get an Alert.
    • If it comes back to Normal -> You get a “Cleared” email (So you can sleep peacefully).
  4. Detailed Report: The email will tell you exactly which 5 processes are eating CPU and which 5 processes are eating RAM.

No complex tools like Nagios or Zabbix. Just one simple file.

The Script: server_watchdog.sh

Copy the code below. I have used basic commands like ps, free, and awk so it will work on any Linux (Ubuntu, CentOS, RedHat).

#!/bin/bash

# --- CONFIGURATION (Change these) ---
EMAIL="[email protected]"
TEMP_FILE="/tmp/server_status_log"

# --- THRESHOLDS ---
WARN_LEVEL=80
CRIT_LEVEL=90

# --- GET SYSTEM VITALS ---
# 1. Get Memory Usage (Percentage)
MEM_USAGE=$(free | grep Mem | awk '{print $3/$2 * 100.0}' | awk '{print int($1)}')

# 2. Get CPU Usage (Percentage - Idle time subtracted from 100)
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}' | awk '{print int($1)}')

# --- GET THE CULPRITS (Process Details) ---
# Get Top 5 CPU eating processes
TOP_CPU_LIST=$(ps -eo pid,ppid,cmd,%cpu --sort=-%cpu | head -n 6)

# Get Top 5 Memory eating processes
TOP_MEM_LIST=$(ps -eo pid,ppid,cmd,%mem --sort=-%mem | head -n 6)

# --- CHECK STATUS ---
CURRENT_STATE="OK"

if [ "$CPU_USAGE" -gt "$CRIT_LEVEL" ] || [ "$MEM_USAGE" -gt "$CRIT_LEVEL" ]; then
    CURRENT_STATE="CRITICAL"
elif [ "$CPU_USAGE" -gt "$WARN_LEVEL" ] || [ "$MEM_USAGE" -gt "$WARN_LEVEL" ]; then
    CURRENT_STATE="WARNING"
else
    CURRENT_STATE="OK"
fi

# --- COMPARE WITH OLD STATE ---
# Check if we have a previous history file
if [ -f "$TEMP_FILE" ]; then
    LAST_STATE=$(cat "$TEMP_FILE")
else
    LAST_STATE="OK"
fi

# --- SEND MAIL IF STATE CHANGES ---
if [ "$CURRENT_STATE" != "$LAST_STATE" ]; then

    # Prepare the Email Body
    BODY_CONTENT="Hi Admin,

Status Update for Server: $(hostname)
--------------------------------------
Current State: $CURRENT_STATE
CPU Usage    : $CPU_USAGE %
Memory Usage : $MEM_USAGE %
--------------------------------------

🔥 TOP 5 CPU CONSUMING PROCESSES:
$TOP_CPU_LIST

💾 TOP 5 MEMORY CONSUMING PROCESSES:
$TOP_MEM_LIST

--------------------------------------
Timestamp: $(date)
"

    # LOGIC: Send Alert if Problem Starts
    if [ "$CURRENT_STATE" == "CRITICAL" ] || [ "$CURRENT_STATE" == "WARNING" ]; then
        SUBJECT="⚠️ ALERT: Server Load is $CURRENT_STATE (CPU: $CPU_USAGE% / MEM: $MEM_USAGE%)"
        echo "$BODY_CONTENT" | mail -s "$SUBJECT" "$EMAIL"
    fi

    # LOGIC: Send Alert if Problem is Solved (Cleared)
    if [ "$CURRENT_STATE" == "OK" ] && ([ "$LAST_STATE" == "CRITICAL" ] || [ "$LAST_STATE" == "WARNING" ]); then
        SUBJECT="✅ CLEARED: Server back to Normal"
        echo "$BODY_CONTENT" | mail -s "$SUBJECT" "$EMAIL"
    fi

    # Update the status in file
    echo "$CURRENT_STATE" > "$TEMP_FILE"
fi

How to Setup? (2 Minute Work)

Step 1: Create the file

Open your terminal and type:

vi server_watchdog.sh

Paste the code above. Change the EMAIL to your actual email id.

Save and exit.

Step 2: Give Permission

Make the script runnable:

chmod +x server_watchdog.sh

Step 3: Test it manually

Run it once to see if you get any error:

./server_watchdog.sh

Note: You won’t get an email if usage is below 80%. To test email, you can temporarily change WARN_LEVEL=10 in the script.

Step 4: Schedule it (Cron Job)

We need this to run automatically every 5 minutes.

Type crontab -e and add this line at the end:

*/5 * * * * /root/scripts/server_watchdog.sh

(Make sure to put the correct path where you saved the file).

Conclusion

That’s it, boss! Now you don’t need to keep logging in to check the server. If memory goes high, the script will catch the specific process (like java, mysql, or php) and mail you immediately.

Happy Scripting! 🚀

Related Posts
Write a comment