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 :
If you use the "free" command, you'll obtain the same information :
We can also do this on a bigger system like this :
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 :
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 :
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
# http://www.christophe-casalegno.com
threshold1=80 # in percent for first reach point
threshold2=90 # in percent for second reach point
host=`hostname -A`
[email protected] # 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
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 http://www.christophe-casalegno.com/tools/memorycheck.sh ; chmod +x memorycheck.sh
-
Christophe Casalegno
https://twitter.com/Brain0verride