Adding Batch Hosts To op5 (Nagios) from CSV

Even with the lovely GUI that op5 comes with, sometimes you need to enter in a large set of hosts into the system.  op5 gives you the ability to use the GUI as well as the historical nagios (hosts.cfg) files.

I wanted a way to not only create a hosts file but include some other items as well like the parent of the device, hostgroups and  image to use.  The input file should be in csv (comma separated format).

So I grabbed some old code on the net that and edited to fit my needs.  There are 3 parts

  • mk_hosts.sh
  • hosts.skel
  • inputfile.csv

mk_hosts.sh:

#!/bin/sh
# mk_hosts.sh
# convert csv input file into hosts.cfg
file=$1
cat $file |while read line;
do
echo "${line}"
NAME=`echo ${line}|cut -d, -f1`
ADDRESS=`echo ${line}|cut -d, -f2`
IMAGE=`echo ${line}|cut -d, -f3`
PARENTS=`echo ${line}|cut -d, -f4`
# Since hostgroups may contain spaces let's put at end and grab everything from field 5 on
HOSTGROUPS=`echo ${line}|cut -d, -f5- | sed -s 's/"//g'`

cat hosts.skel | sed -e "s/TEMP_NAME/$NAME/" -e "s/TEMP_IP/$ADDRESS/" -e "s/TEMP_HOSTGROUPS/$HOSTGROUPS/" -e "s/TEMP_IMG/$IMAGE/" -e "s/TEMP_PARENTS/$PARENTS/" >>hosts.cfg
done

hosts.skel:

define host{
use default-host-template
host_name TEMP_NAME
alias TEMP_NAME
address TEMP_IP
hostgroups TEMP_HOSTGROUPS
icon_image TEMP_IMG
statusmap_image TEMP_IMG
parents TEMP_PARENTS
}

inputfile.csv

oracle-prod1,172.2.6.32,redhat.png,ny-router-1,"All Servers, NY DataCenter, Everything, Prod Servers, Linux Servers"
oracle-prod2,172.2.6.33,redhat.png,ny-router-1,"All Servers, NY DataCenter, Everything, Prod Servers, Linux Servers"
oracle-prod3,172.2.6.34,redhat.png,ny-router-1,"All Servers, NY DataCenter, Everything, Prod Servers, Linux Servers"
win-exchange,172.4.6.32,windows.png,ny-router-1,"All Servers, NY DataCenter, Everything, Prod Servers, Window Servers"

Your CSV file should use the following columns:

Name, IP, Image_Name, Parent_Name, HostGroup(s)

Once you have done this simply run the command (outside of your etc dir):

./mk_hosts.sh inputfile.csv

Now look at the newly created file hosts.cfg

If everything looks good, simply cat >> this onto the end of the hosts.cfg file.  Within op5, goto config and it will notice you have a NEWER config.  Click save and all is well.  If not, go back and fix the errors.

BTW: You might want to create a backup within op5 before doing this just in case you lay down some wrong hosts.

Leave a Reply

Your email address will not be published.