Skip to content

Instantly share code, notes, and snippets.

@komeda-shinji
Created December 13, 2017 08:38
Show Gist options
  • Save komeda-shinji/699a19fa410969b6db95a82e8b39c957 to your computer and use it in GitHub Desktop.
Save komeda-shinji/699a19fa410969b6db95a82e8b39c957 to your computer and use it in GitHub Desktop.
#!/bin/bash
NAGIOS_OK=0
NAGIOS_WARNING=1
NAGIOS_CRITICAL=2
NAGIOS_UNKNOWN=3
PROGNAME="check_reachable"
VERSION="1.0"
print_usage() {
echo "$PROGNAME $VERSION"
echo "Usage:"
echo "$PROGNAME -H TARGET -m HOP -r hop:ROUTE1[,hop2:ROUTE2[,:ROUTE3]]"
echo " "
echo "Example:"
echo "$PROGNAME -H 8.8.8.8 -r 3:192.168.1.254,192.168.2.254"
}
declare -a ROUTE
while getopts dH:l:m:p:r:STw: OPT; do
case "$OPT" in
d) DEBUG=1;;
H) TARGET="$OPTARG";;
l) LIMIT="$OPTARG";;
m) MAXTTL="$OPTARG";;
p) PORT="$OPTARG";;
r) ROUTE[${#ROUTE[@]}]="$OPTARG";;
S) SUDO="sudo";;
T) METHOD="-T";;
w) WAIT="$OPTARG";;
esac
done
if [ -z "$TARGET" ]; then
print_usage
exit $NAGIOS_UNKNOWN
fi
ERRCODE=$NAGIOS_OK
METHOD=${METHOD:-"-I"}
LIMIT=${LIMIT:-3}
declare -a output
coproc { $SUDO traceroute ${MAXTTL:+'-m'} $MAXTTL ${WAIT:+'-w'} $WAIT $METHOD ${PORT:+'-p'} $PORT $TARGET 2>&1; } &
while read -u ${COPROC[0]} hop line 2>/dev/null; do
if [[ $hop =~ [[:digit:]][[:digit:]]* ]]; then
output[$hop]="$hop: $line"
elif [ $hop = "traceroute" ]; then
header="$hop $line"
else
ERRCODE=$NAGIOS_UNKNOWN
ERRMSG="$ERRMSG${ERRMSG:+ }$hop $line"
output[${#output[@]}]="$hop $line"
fi
[ -n "$DEBUG" ] && echo "$hop: $line"
if [ "$line" = "* * *" ]; then
if [ -z "$unreachable" ]; then
unreachable=$hop
elif [ "$hop" -ge "$((unreachable + $LIMIT))" ]; then
kill -TERM $COPROC_PID
break
fi
else
unreachable=
fi
done
wait $COPROC_PID >/dev/null 2>&1
status=$?
[ -n "$DEBUG" ] && echo $status
if [ -n "$unreachable" ]; then
echo "ERROR $TARGET: unreachable after hop $((unreachable - 1))"
i=$((unreachable - 3))
if [ $i -le 0 ]; then
i=0
fi
while [ $i -le $unreachable ]; do
echo "${output[$i]}"
i=$((i + 1))
done
exit $NAGIOS_CRITICAL
fi
k=0
while [ $k -lt ${#ROUTE[@]} ]; do
oIFS="$IFS"
IFS=",$IFS"
set -- ${ROUTE[$k]}
IFS="$oIFS"
found=
declare -a gateways=($@)
for gw in ${gateways[@]}; do
case "$gw" in
*:*)
h=$(expr $gw : '\([1-9][0-9]*\):.*')
r=$(expr $gw : '.*:{0,1}\(.*\)')
;;
*)
r="$gw"
;;
esac
if [ -n "$h" ]; then
case "${output[$h]}" in
*"$r"*) found=$h;;
*) ERRCODE=$NAGIOS_WARNING; break;;
esac
else
i=0
while [ $i -le ${#output[@]} ]; do
case "${output[$i]}" in
*"$r"*) found=$i; break;;
esac
i=$((i + 1))
done
fi
done
if [ -z "$found" ]; then
ERRCODE=$NAGIOS_WARNING
break
fi
k=$((k + 1))
done
hop=${#output[@]}
if [ "$ERRCODE" -eq "$NAGIOS_OK" ]; then
echo "OK ${output[$hop]}"
else
echo "ERROR $ERRMSG"
fi
exit $ERRCODE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment