Christophe Casalegno

How to simply check free memory and take action when a threshold is reached

In your admin work it can be useful to check free memory and take action on threshold. The most tools don’t show you a realistic state of your memory. For example if you launch « top » command on a server, you’ll obtain an information like this :

memorycheck1

If you use the « free » command, you’ll obtain the same information :

memorycheck2

We can also do this on a bigger system like this :

memorycheck3
memorycheck4

But this resultat aren’t really the true, just because Linux loves buffers & cache. Now if we try to use htop instead of top or free you’ll obtain a different information.

On the second system :

memorycheck4
memorycheck5

So if you want to really take action if you have a memory problem you’ll need to obtain the good information. We can do this with free, awk, print & sed in one line like this :


free | awk 'FNR == 3 {print $4/($3+$4)*100-100}'| sed 's/-//g'

 
Example :

memorycheck6

Now we just need to write a shell script to monitor this and take action if there is a problem like this :


#!/bin/bash
# A simple shell script that take action when occupied memory reach a threshold
# Author : Christophe Casalegno
# https://twitter.com/Brain0verride
# https://www.christophe-casalegno.com
threshold1=80 # in percent for first reach point
threshold2=90 # in percent for second reach point
host=`hostname -f`
alert=alerte@nospam.com # Email for receiving alerts
logfile="/var/log/memory.log"
# Calculate real occupied memory in percent
realmem=`free | awk 'FNR == 3 {print $4/($3+$4)*100-100}'| sed 's/-//g' |cut -d "." -f1`
if [ "$realmem" -gt "$threshold1" ]
then
date=`date`
echo "The memory usage has reached $realmem% on $host" | mail -s "$host : High Memory Usage Alert" $alert
echo "$date : The memory usage has reached $realmem% on $host." >> $logfile
if [ "$realmem" -gt "$threshold2" ]
then
echo "The memory usage has reached $realmem% on $host" | mail -s "$host : Very High Memory Usage Alert" $alert
echo "$date : Alert T2 : The memory usage has reached $realmem% on $host." >> $logfile
# Put your own urgency commands here
fi
fi

I use 2 threshold values but you can use more or less if you need. No you just have to replace emailing & logging by the actions you want. After, just put it in your crontab.

You can download the script directly here : memorycheck or from your server :

wget --no-check-certificate https://www.christophe-casalegno.com/tools/memorycheck.sh ; chmod +x memorycheck.sh

Christophe Casalegno
​Vous pouvez me suivre sur : Twitter | Facebook | Linkedin | Telegram | Youtube

1 Commentaire

  1. Pingback: Bash : how to simply check disk space on linux and take action when a threshold is reached | Christophe Casalegno

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *