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:

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

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


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 :


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 :

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