Bash script to get process consuming high memory in server

Pre-requiste : To run this script the server should be able to send email.
You should also be able to run cron job.

The script will let you know the process ID along with the application consuming high memory in the server, it will greatly help you to identify the same when the server crashes, the script basically sends mail once there is high memory consumption in your server. You can define the limit here as per your requirement, i.e; if there is only 200 MB or below of free memory in your server you will get alert via email.

#!/bin/bash
COUNT=0
# Set the memory limit here, below this limit will shoot mail alert
THRESHOLD=200
SUBJECT=”SERVER CRITICAL: LOW MEMORY”
# The mail address you want to get alert
MAIL=”mail@example.com”
# Output of the script will be stored here
MEM_CONSUME=”/tmp/mem_consume.txt”
MEM_USAGE=`free -m | awk ‘NR==2 {print $4 }’`
# The function will check for 10 seconds if memory is less than Threshold, will shoot email once this condition is satisfied
function check_mem(){
if [ “$MEM_USAGE” -lt “$THRESHOLD” ]; then
COUNT=$((++COUNT))
sleep 5
if [ “$COUNT” -eq 2 ]; then
echo -e “Current free memory is : $MEM_USAGE \n” > $MEM_CONSUME
echo -e “Memory details :\n `free -m` \n” >> $MEM_CONSUME
echo “The process consuming highest memory :” >> $MEM_CONSUME
echo -e “————————————–\n” >> $MEM_CONSUME
# Displays process ID along with application consuming highest memory
ps -e -orss=,args= | sort -nr | head | awk ‘{ print int($1/1024)”M\t”$2 }’ >> $MEM_CONSUME
/bin/mail -s “$SUBJECT” “$MAIL” < $MEM_CONSUME
exit
else
check_mem
fi
else exit
fi
}
check_mem

Set a cron job to run this script every 2 seconds

*/2 * * * * /path to the script/mem-check.sh

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *