Christophe CasalegnoAutoimmune warrior, Entrepreneur & Bio/Hacker

brain@127.0.0.1:~$ cat post.html

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 when a threshold is reached. Most tools don’t show you a realistic picture of your memory usage. For example, if you run the “top” command on a server, you’ll get information like this:

memorycheck1

If you use the “free” command, you’ll get the same information:

memorycheck2

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

memorycheck3
memorycheck4

But these results don’t really reflect reality, simply because Linux loves buffers and cache. Now, if we try using htop instead of top or free, we get different information.

On the second system :

memorycheck4
memorycheck5

So, if you really want to take action when you have a memory problem, you’ll need the right information. We can get it with free, awk, print and 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 two thresholds, but you can use more or fewer if you need to. Now just replace emailing and logging with the actions you want. Then 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
https://all.bo

1 comment

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

Leave a comment

Add a comment
Christophe Casalegno Brain 0verride

Keep it simple
and direct!