-------26----张立----

下面是在网上找到的脚本写的很好,经验证没有错误可以使用。

我分析下原理并做相应的批注。

原理:通过free -m命令 过滤出total free used (free=free+catch)不同字段的数值,计算出空闲内存的百分比,计算公式为% free = ((free mem / total mem) * 100),并设定warning和critical的值,当%free<critical exit 2  ;%free<warning exit 1;%free>critical exit 0;

########################################

vim check_memary

#!/bin/bash
USAGE="`basename $0` [-w|--warning]<percent free> [-c|--critical]<percent free>"
THRESHOLD_USAGE="WARNING threshold must be greater than CRITICAL: `basename $0` $*"
calc=/tmp/memcalc
percent_free=/tmp/mempercent
critical=""
warning=""
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

#######################################
# print usage
if [[ $# -lt 4 ]]
then
        echo ""
        echo "Wrong Syntax: `basename $0` $*"
        echo ""
        echo "Usage: $USAGE"
        echo ""
        exit 0
fi

########################################给-w 和-c 参数赋值
# read input
while [[ $# -gt 0 ]]
  do
        case "$1" in
               -w|--warning)
               shift
               warning=$1
        ;;
               -c|--critical)
               shift
               critical=$1
        ;;
        esac
        shift
  done

########################################检验-w是否大于-c

# verify input
if [[ $warning -eq $critical || $warning -lt $critical ]]
then
        echo ""
        echo "$THRESHOLD_USAGE"
        echo ""
        echo "Usage: $USAGE"
        echo ""
        exit 0
fi

#######################################取值
# Total memory available
total=`free -m | head -2 |tail -1 |gawk '{print $2}'`
# Total memory used
used=`free -m | head -2 |tail -1 |gawk '{print $3}'`
# Calc total minus used
free=`free -m | head -2 |tail -1 |gawk '{print $4+$7}'`
# normal values

#############################用dc工具计算的,感觉这个比较麻烦,不如直接计算
# make it into % percent free = ((free mem / total mem) * 100)
echo "5" > $calc # decimal accuracy
echo "k" >> $calc # commit
echo "100" >> $calc # multiply
echo "$free" >> $calc # division integer
echo "$total" >> $calc # division integer
echo "/" >> $calc # division sign
echo "*" >> $calc # multiplication sign
echo "p" >> $calc # print
percent=`/usr/bin/dc $calc|/bin/sed 's/^\./0./'|/usr/bin/tr "." " "|/usr/bin/gawk {'print $1'}`

#######################################
if [[ "$percent" -le  $critical ]]
        then
                echo "CRITICAL - $free MB ($percent%) Free Memory"
                exit 2
fi
if [[ "$percent" -le  $warning ]]
        then
                echo "WARNING - $free MB ($percent%) Free Memory"
                exit 1
fi
if [[ "$percent" -gt  $warning ]]
        then
                echo "OK - $free MB ($percent%) Free Memory"
                exit 0
fi