22 января 2013 г.

Мониторим коммутатор по OIDу

#!/bin/sh
NAGIOS_OK=0
NAGIOS_WARNING=1
NAGIOS_CRITICAL=2

#KEY_SNMP="public"
#IP="10.14.0.20"
#OID=".1.3.6.1.2.1.2.2.1.14"
#NAME_OID="InErrors"

print_usage() {
    PROGNAME=`basename $0`
    echo "Usage: $PROGNAME -h <IP ADDRESS SWITCH> -k <SNMP KEY> -o <OID> -n <NAME OID> -w <WARNING> -c <CRITICAL>"
}
if [ $# -lt 12 ]; then
    print_usage
    exit $NAGIOS_WARNING
fi
while getopts "h:k:o:n:w:c:" Option
 do
    case $Option in
    h) IP=$OPTARG;;
    k) KEY_SNMP=$OPTARG;;
    o) OID=$OPTARG;;
    n) NAME_OID=$OPTARG;;
    w) WARN=$OPTARG;;
    c) CRIT=$OPTARG;;
esac
done

OID_PORTS="/tmp/$NAME_OID-ports-$IP"
RES_NEW="/tmp/$NAME_OID-new_res-$IP"
RES_OLD="/tmp/$NAME_OID-old_res-$IP"
RESULT="/tmp/$NAME_OID-RESULT-$IP"

new_to_old() {
    cp $RES_NEW $RES_OLD
    rm $RES_NEW
}

CMD=`snmpwalk -c $KEY_SNMP -v 2c $IP $OID | awk '{print $4}' > $RES_NEW`
REQUEST=`cat $RES_NEW | wc -l | awk '{print $1}'`

if [ "$REQUEST" -eq "0" ]; then
    echo "SNMP NOT CONNECTED"
    exit $NAGIOS_CRITICAL
fi
if [ -f $RES_OLD ]; then
    FIND_PORTS=`diff $RES_OLD $RES_NEW | grep "c" | sed -re 's/\c.*$//' > $OID_PORTS`
    TESTFILE=`wc -l $OID_PORTS | awk '{print $1}'`
if [ $TESTFILE -eq 0 ]; then
    echo "All ports OK"
    new_to_old
    exit $NAGIOS_OK
else
    IN=`cat $OID_PORTS`
    for i in $(echo $IN); do 
        NEW=`cat $RES_NEW | head -n$i | tail -n1`
        OLD=`cat $RES_OLD | head -n$i | tail -n1`
        SUM=$(($NEW-$OLD))
        if [ "$SUM" -gt "$CRIT" ]; then
            echo "port:$i count:$SUM status=CRIT;;"
        fi
        if [ "$SUM" -gt "$WARN" ]; then
            echo "port:$i count:$SUM status=WARN;;"
        else
            echo "port:$i count:$SUM status=OK;;"
        fi
    done > $RESULT
    cat $RESULT | xargs
    WC=`cat $RESULT | grep CRIT | wc -l | awk '{print $1}'`
    if [ $WC -gt "0" ]; then
    status=$NAGIOS_CRITICAL
    else
    status=$NAGIOS_WARNING
    fi
    new_to_old
    rm $RESULT
    exit $status
fi
else
    echo "First run!"
    new_to_old
    exit $NAGIOS_WARNING
fi