#!/bin/sh

# checks that a machine is listening on a TCP port

# we could normally check for
# tcp.tcpConnTable.tcpConnEntry.tcpConnState.0.0.0.0.$PORT.0.0.0.0.0
# but windows seems to report a "random" number for remPort on a listening
# connection, which seems wrong somehow

# so we walk
# tcp.tcpConnTable.tcpConnEntry.tcpConnState.0.0.0.0.$PORT.0.0.0.0
# and look for $3 == "listen(2)"

# by default we look on the local address of 0.0.0.0, which means all
# interfaces, but we could also provide a specific IP (e.g. 127.0.0.1)
# if the port is only listening on a certain IP (e.g. is local only)

# - John Sellens


# this is fairly specific ...

PATH=/usr/local/nagios/libexec:/usr/local/bin:/bin:/usr/bin
export PATH

myname=`basename "$0"`

usage="$myname hostname community port [ipaddress]"

# this is enterprises.itwatchdogs.wxGoos.internalTable.internalEntry
# tcp.tcpConnTable.tcpConnEntry.tcpConnState
oid=".1.3.6.1.2.1.6.13.1.1"


ipaddress="0.0.0.0"
if [ $# -eq 4 ]; then
    ipaddress="$4"
elif [ $# -ne 3 ]; then
    msg="$myname: missing or too many arguments: Usage: $usage"
    echo "$msg"
    exit 3
fi
host="$1"
comm="$2"
port="$3"
fulloid="$oid.${ipaddress}.${port}.0.0.0.0"

# we set an empty MIBS to avoid looking up in the mib files
ans=`env MIBS="" snmpwalk -c "$comm" "$host" "$fulloid"`
res=$?

if [ "$res" -ne 0 ]; then
    msg="Error: snmpwalk failed: $ans"
    res=3	# unknown
else
    val=`echo "$ans" | awk '{print $NF}'`
    # if [ "$val" == "listen(2)" ]; then
    if [ "$val" == "2" ]; then
	msg="OK: listening on TCP $ipaddress / $port"
	res=0	# OK
    else
	msg="CRITICAL: NOT listening on TCP $ipaddress / $port"
	res=2	# critical
    fi
fi

echo "$msg"
exit "$res"
