Send email when server is running out of memory

Sometimes we have a server with low resources, so we need a way to get an alert when this is becoming critical. For example, we can send us an email when the server is running out of memory.

I found a script made by Aaron Kili Kisinga that does exactly that, so I made some changes to use mpack instead of mailx. Here’s the result:

#!/bin/bash 
#######################################################################################
#Script Name    :lowmemoryalert.sh
#Description    :send alert mail when server memory is running low
#Args           :       
#Author         :Santiago Valdez based on Aaron Kili Kisinga script
#Email          :hola@santiagovaldez.me
#License       : GNU GPL-3      
#######################################################################################
## declare mail variables
##email subject 
subject="WARNING! Server is running out of memory"
##sending mail as
#from="server.monitor@example.com"
## sending mail to
to="fulano@gmail.com"
## send carbon copy to
also_to="mengano@gmail.com"

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

#echo -e "LIBRE $free \n"

## check if free memory is less or equals to  250MB
if [[ "$free" -le 250  ]]; then
        ## get top processes consuming system memory and save to temporary file 
        ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head >/tmp/top_proccesses_consuming_memory.txt

        file=/tmp/top_proccesses_consuming_memory.txt
        ## send email if system memory is running low
        echo -e "Atention!, the server is running out of memory!\n\nFree Memory: $free MB\n\n\nThe list of the processes with most memory consumption is attached.\n\n" > /tmp/bodyemail.txt
        body=/tmp/bodyemail.txt
        
        mpack -d "$body" -s "$subject" "$file" "$to" "$also_to"
fi

exit 0

With this simple bash script we can have an alert whenever the server is getting to a critical low memory state.

Compartí el post, no seas careta...Tweet about this on Twitter
Twitter
Share on Facebook
Facebook
0Share on Tumblr
Tumblr
0Share on LinkedIn
Linkedin

Entradas recientes

Comentarios recientes

Archivos

Categorías

Santi Escrito por:

Sé el primero en comentar

Deja un comentario