Nagios subnet scanner


#1

This will need some fine tuning for most people (it’s specific to my network at the moment), but the following little code will scan a specified subnet for all active hosts, find their hostname and then add them to a config file using the ‘generic-host’ template (these will then need to be added to a hostgroup - the code will add all the hosts found to the hostgroup.)

$HOSTCFGFILE=hosts.cfg.backup

function subnetScan {
IP=`nmap -sP 127.0.0.1/8 | awk '/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/' | tr -d '()' | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}'`
for i in $IP
        do
                hostname=`host $i | awk '{print $5}'`
                HOST=${hostname%%.*}
                case $HOST in
                "3(NXDOMAIN)")
                        echo "$i cannot be added to added to nagios."
                ;;
                *)
                        echo "define host{" >> $HOSTCFGFILE
                        echo " use                              generic-host" >> $HOSTCFGFILE
                        echo " host_name                        $HOST" >> $HOSTCFGFILE
                        echo " alias                            $HOST" >> $HOSTCFGFILE
                        echo " address                          $i" >> $HOSTCFGFILE
                        echo "}" >> $HOSTCFGFILE
                        echo "" >> $HOSTCFGFILE
                #fi
                ;;
                esac
        done

addHostgroup
for HOST in `cat $HOSTCFGFILE | grep -B 1 address | grep alias | awk '{print $2}' | uniq | tr ' ' ','`
        do
                MEMBERS=`cat $HOSTCFGFILE | grep hostgroup_name | awk '{print $2}'`
                sed -i "/hostgroup_name.*${MEMBERS}/,/}/s/\(members.*\)/\1,$HOST/" $HOSTCFGFILE
        done
}

function addHostgroup {
if  -z `cat $HOSTCFGFILE | grep hostgroup` ]]; then
        echo "Creating new hostgroup(s), this can be multiple names for multiple hostgroups seperated by a space."
        echo -n "Specify name(s) for the hostgroup: "
        read HGNAME
                for name in $HGNAME
        do
                echo " define hostgroup{" >> $HOSTCFGFILE
                echo " hostgroup_name                   $name" >>  $HOSTCFGFILE
                echo " alias                                    $name" >>  $HOSTCFGFILE
                echo " members                                  " >>  $HOSTCFGFILE
                echo "}" >>  $HOSTCFGFILE
                echo "" >> $HOSTCFGFILE
        done
fi
}

subnetScan

I’ve actually got code to completely configure a basic version of nagios - obviously agent installation etc isn’t possible (yet… have ideas about remotely executing code on servers). If anyones interested I can post this (will need some heavy editing as it’s specific to the company I work for).