Skip to content

Instantly share code, notes, and snippets.

@q1x
Created February 19, 2015 12:24
Show Gist options
  • Save q1x/b37d74152646bcd65333 to your computer and use it in GitHub Desktop.
Save q1x/b37d74152646bcd65333 to your computer and use it in GitHub Desktop.
snmp-discovery
#!/bin/bash
#
# This script can be used to perform Zabbix Low-Level Discoveries of
# SNMP hosts on the network via the 'nmap', 'snmpget' and 'host' utilities.
#
# Advantages over normal network discovery:
# * Faster!
# * We can fetch the hostname via SNMP (no more IP based names when PTR records are missing)
# * We can use the highly flexible 'nmap' targetting
#
# For SNMP versions 1 and 2 call it like this:
#
# snmp-discovery <HOSTNAME> <DISCOVERY ITEM> <SNMPVERSION> <TARGET> <SNMP_COMMUNITY> <SNMP_TIMEOUT>
#
# <TARGET> is a 'nmap' target string (see 'man nmap').
#
# Set up used commands, edit these if you are having path problems.
SNMPGET="snmpget"
NMAP="nmap"
HOST="host"
SED="sed"
AWK="awk"
GREP="grep"
TAIL="tail"
#
# We use Volter Frohlichs' 'csv-to-LLD' python script for the conversion to LLD JSON.
# Get it here: http://www.geofrogger.net/review/csv-to-lld.py
# More info can be had here: https://www.zabbix.org/wiki/Csv-to-lld
#
CSVTOLLD=/opt/zabbix/externalscripts/csv2lld.py
# We also need 'zabbix_sender'.
ZABBIXSENDER=/usr/sbin/zabbix-sender
#
# Setup vars
#
SNMPVER="$3"
SNMPTIMEOUT="0.2"
ZBXSERVER="127.0.0.1"
ZBXPORT="10051"
#
# Declare discovery function (outputs CSV)
#
discover() {
HEADER="\"HOSTNAME\",\"IPADDR\",\"DNSNAME\""
echo $HEADER
for IP in $($NMAP -sn -oG - "$1" | $GREP 'Status: Up' | $AWK '{print $2}'); do
HOSTNAME="$($SNMPCMD $IP sysName.0 2> /dev/null | $AWK '{print $4}')"
if [[ "$HOSTNAME" != "" ]]; then
LOOKUP=$($HOST $IP)
[[ $? -eq 0 ]] && DNSNAME=$(echo $LOOKUP | $TAIL -n 1 | $AWK '{print $NF}' | $SED 's/\.$//') || DNSNAME=""
echo "\"$HOSTNAME\",\"$IP\",\"$DNSNAME\""
fi
done
}
#
# See if we have a valid SNMP version and construct the full 'snmpget' command.
#
case "$SNMPVER" in
1)
TARGET="$4"
COMMUNITY="$5"
[[ "$6" != "" ]] && SNMPTIMEOUT=$6
SNMPCMD="$SNMPGET -t \"$SNMPTIMEOUT\" -v \"$SNMPVER\" -c \"$COMMUNITY\""
;;
2c)
TARGET="$4"
COMMUNITY="$5"
[[ "$6" != "" ]] && SNMPTIMEOUT=$6
SNMPCMD="$SNMPGET -t $SNMPTIMEOUT -v $SNMPVER -c $COMMUNITY"
;;
3)
echo "SNMP version not supported yet." >&2
exit 1
;;
*)
echo "Please specify SNMP version." >&2
exit 1
;;
esac
#
# See if we can use CSV-TO-LLD and ZABBIX_SENDER, if so run the discovery. Else exit.
#
if [[ -x "$CSVTOLLD" ]]; then
if [[ -x "$ZABBIXSENDER" ]]; then
DISCOVERY=$(discover "$TARGET" | $AWK 'NR<2{print $0;next}{print $0| "sort -u -t, -k1,1"}' | $CSVTOLLD -d ",")
echo "$1 $2 $DISCOVERY" | $ZABBIXSENDER -v -z "$ZBXSERVER" -p "$ZBXPORT" -i -
else
echo "ZABBIX_SENDER is not found or usable." >&2
exit 1
fi
else
echo "CSV-TO-LLD script is not found or usable." >&2
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment