-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcpu_memory_monitor.sh
More file actions
60 lines (47 loc) · 2.06 KB
/
cpu_memory_monitor.sh
File metadata and controls
60 lines (47 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash
# =====================================================
# Script Name : cpu_memory_monitor.sh
# Purpose : Monitor CPU and Memory usage with alert system
# Usage : ./cpu_memory_monitor.sh
# =====================================================
# Thresholds (You can adjust based on your environment)
CPU_THRESHOLD=80
MEM_THRESHOLD=80
# Log file location
LOG_FILE="/var/log/cpu_memory_monitor.log"
# System details
HOST=$(hostname)
DATE=$(date +"%Y-%m-%d %H:%M:%S")
# Fetch current CPU and Memory usage
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print 100 - $8}') # % usage excluding idle
MEM_USAGE=$(free | awk '/Mem/{printf("%.2f"), $3/$2 * 100}')
echo "[$DATE] Checking system resource usage on $HOST..." >> $LOG_FILE
# Check CPU usage
if (( ${CPU_USAGE%.*} >= CPU_THRESHOLD )); then
echo "[$DATE] ALERT: High CPU usage detected - ${CPU_USAGE}%!" | tee -a $LOG_FILE
# Optional email alert
# echo "CPU usage is at ${CPU_USAGE}% on $HOST" | mail -s "CPU Alert: $HOST" [email protected]
else
echo "[$DATE] CPU usage normal: ${CPU_USAGE}%" >> $LOG_FILE
fi
# Check Memory usage
if (( ${MEM_USAGE%.*} >= MEM_THRESHOLD )); then
echo "[$DATE] ALERT: High Memory usage detected - ${MEM_USAGE}%!" | tee -a $LOG_FILE
# Optional email alert
# echo "Memory usage is at ${MEM_USAGE}% on $HOST" | mail -s "Memory Alert: $HOST" [email protected]
else
echo "[$DATE] Memory usage normal: ${MEM_USAGE}%" >> $LOG_FILE
fi
echo "[$DATE] Resource usage check completed." >> $LOG_FILE
# ⚙️ How It Works
# Step Description
# top -bn1 Runs top in batch mode once for CPU stats
# awk '{print 100 - $8}' Calculates used CPU as 100 - idle%
# `free awk '/Mem/{...}'`
# Threshold comparison Alerts if usage exceeds the defined limit
# tee -a $LOG_FILE Logs and prints alert simultaneously
# 💡 Example Output
# [2025-10-30 12:34:18] Checking system resource usage on ip-172-31-25-181...
# [2025-10-30 12:34:18] ALERT: High CPU usage detected - 91.3%!
# [2025-10-30 12:34:18] Memory usage normal: 67.8%
# [2025-10-30 12:34:18] Resource usage check completed.