Last active
November 20, 2024 11:07
-
-
Save santhoshvr/bd6db5b1cab4f8d181d2ac2b59dd08aa to your computer and use it in GitHub Desktop.
This shell script monitors the server load average and sends an email notification if it exceeds a dynamically calculated threshold based on the number of CPU cores. It also identifies the process with the highest CPU usage. This script can be scheduled to run periodically using a cron job.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#/bin/bash | |
# Get the number of CPU cores | |
CPU_CORES=$(nproc) | |
# Calculate the threshold based on CPU cores, 0.7 -> indicates the 70% of CPU usage | |
THRESHOLD=$(echo "$CPU_CORES * 0.7" | bc -l) | |
# Email recipient | |
EMAIL="[email protected]" | |
# Get the 1-minute load average | |
LOAD_AVERAGE=$(uptime | awk -F'average:' '{ print $2 }' | awk '{gsub(",", "", $1); print $1}') | |
# Check if load average exceeds the threshold | |
if (( $(echo "$LOAD_AVERAGE > $THRESHOLD" | bc -l) )); then | |
# Get the process with the highest CPU usage | |
TOP_PROCESS=$(ps -eo pid,%cpu,cmd --sort=-%cpu | head -n 10) | |
# Send an email notification | |
SUBJECT="Server Load High - $LOAD_AVERAGE" | |
BODY="The server load average is above the threshold. Load average: $LOAD_AVERAGE\n\nTop process:\n$TOP_PROCESS" | |
echo -e "SUBJECT: $SUBJECT \n\nMAIL BODY: $BODY" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To manually increase the system load average in Linux. Refer this command:
openssl speed -multi $(grep -ci processor /proc/cpuinfo)
or (if nproc is present)
openssl speed -multi $(nproc --all)
OpenSSL is almost always present on nowadays distros, so no extra packages needed.