Bash Script to Check Memory with Email Alert when Low

From Brian Nelson Ramblings
Revision as of 00:35, 8 November 2018 by Brian (Talk | contribs) (Created page with "==Bash Script to Check Memory with Email Alert when Low== One of the critical components of a server is memory (RAM), it greatly impacts on overall performance of a system....")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Bash Script to Check Memory with Email Alert when Low

One of the critical components of a server is memory (RAM), it greatly impacts on overall performance of a system.

In this how-to, we will share a small but useful shell script to send an alert email to one or more system administrator(s), if server memory is running low.

This is script is particularly useful for keeping an eye on Linux VPS (Virtual Private Servers) with small amount of memory, say of about 4GBs.

This is how the bsCheckMemory.script script works: first it checks the free memory size, then determines if amount of free memory is less or equal to a specified size (50 MB for the purpose of this guide)

If this condition is true, it will generate a list of the top 10 processes consuming server RAM and sends an alert email to specified email addresses.

MemoryCheck Script

#!/bin/bash 
########################################
## declare mail variables
##email subject 
subject="Server Memory Status Alert"
##sending mail as
from="[email protected]"
## sending mail to
to="[email protected]"
## send carbon copy to
##Like to also send to my phone 
also_to="[email protected]"

## get total free memory size in megabytes(MB) 
free=$(free -mt | grep Total | awk '{print $4}')

## check if free memory is less or equals to  50MB
if  "$free" -le 50  ; then
        ## get top processes consuming system memory and save to temporary file 
        ps aux --sort -rss | head -n11 >/tmp/top_memory.txt 

        file=/tmp/top_memory.txt
        ## send email if system memory is running low
        echo -e "Warning, server memory is running low!\n\nFree memory: $free MB" | mail -a "$file" -s "$subject" -r "$from" -c "$to" "$also_to"
fi

exit 0

--Note you may need to make a few changes depending on the memory limit you set and the mail program used to send the Alerts

Setting up the Cron

I would suggest running the script every few minutes to get the best results

Example command if script was saved in the /root directory

chmod +x /root/bsCheckMemory.script

Edit your crontab

crontab -e

Then add

*/5 * * * * /bin/bash /root/bsCheckMemory.script >/dev/null 2>&1

Now you will get an alert when your memory gets below your threshold.