Question: Create a shell script that monitors the CPU and memory usage on a Linux system and logs any usage over 80% to a file.
#!/bin/bash
LOG_FILE="/var/log/system_health.log"
# Function to check CPU usage
check_cpu() {
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}')
CPU_USAGE_VAL=$(echo $CPU_USAGE | sed 's/%//')
if (( $(echo "$CPU_USAGE_VAL > 80" |bc -l) )); then
echo "$(date): High CPU usage detected: $CPU_USAGE" >> $LOG_FILE
fi
}
# Function to check memory usage
check_memory() {
MEM_USAGE=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if (( $(echo "$MEM_USAGE > 80" |bc -l) )); then
echo "$(date): High Memory usage detected: $MEM_USAGE%" >> $LOG_FILE
fi
}
# Main monitoring function
monitor_system() {
while true; do
check_cpu
check_memory
sleep 60
done
}
# Start monitoring
monitor_system
No comments:
Post a Comment