checkMemory.sh

d
Nombre: checkMemory.sh
Autor: Cristian Hernandez
Descripcion: Monitorea el uso total de la memoria.
#!/bin/bash
#===============================================================================
# Author:
#               Cristian Hernandez

#===============================================================================
#
# Description:
#           Monitor total memory usage.
#
# Parameters:
#       -w: Warning threshold (in percentiles)
#       -c: Critical threshold (in percentiles)
#       -h: Help message
#
#===============================================================================

#
# FUNCTIONS:
#
#-------------------------------------------------------------------------------
# Check CPU activity. Returns OK, WARNING or CRITICAL status based on command
# line arguments
function check_memory() {
    local warning=$1
    local critical=$2
    local results=($(free -m | awk 'BEGIN {
                total=0;
                rss=0
            }
            {
                if ($1 == "Mem:") {
                    total=$2; # Memory total
                    vmz=$3;   # Memory in use (VMZ)
                }
                if ($1 == "-/+") {
                    rss=$3         # Memory in use (RSS)
                    cache=vmz-$3;  # Memory in cache
                }
            }
            END {
                # Return array of results: [percent_memory_used, memory_in_cache]
                print int(rss/total*100), cache

            }'))

    echo "Current:${results[0]} Threshold:[${warning}/${critical}]% Cache:${results[1]}MB"
    # Check status and exit accordingly
    [ "${results[0]}" -gt "$critical" ] && exit 2
    [ "${results[0]}" -gt "$warning" ] && exit 1

    exit 0

}

#-------------------------------------------------------------------------------

# Help message
function usage() {
    echo "Usage:
    -w: Warning threshold (in percentiles, i.e. from 0 to 100)
    -c: Critical threshold (in percentiles, i.e. from 0 to 100)
    -h: This Help message

    Example: $0 -w 70 -c 90"
}

#-------------------------------------------------------------------------------

#
# MAIN:
#

#-------------------------------------------------------------------------------

# Check command line options

while getopts 'c:w:h' OPT
do
    case $OPT in
        w) warning=${OPTARG}
        ;;
        c) critical=${OPTARG}
        ;;
        h) usage && exit 1
        ;;
    esac
done

# Validate command line arguments
if [ $# -eq 4 ]; then
    if [ "$critical" -gt "$warning" ]; then
        # Check memory usage and exit accordingly
        check_memory $warning $critical
    else
        echo "ERROR: critical threshold must be greater than warning threshold"
        usage
        exit 1
    fi
else
    echo "ERROR: Missing argument!"
    usage
    exit 1
fi

0 comentarios: