Export hosts.cfg data to CSV file?


#1

Does anyone know if there is an existing script, tool, etc that reads through the nagios config file (hosts.cfg for my needs) and can export the data into a CSV format ?

So like,

define host {
host_name server2
alias NagiosServer
address 1.2.3.4
use generic-template
}

I need CSV output for host_name, alias, and address parameters, then need it to go on to next host and add another line to file.

server2, NagiosServer, 1.2.3.4


#2

Maybe there is, but it is really easy to write a shell script that would do that thing for you.
I’ve tried to write something that would do the thing, try it and modify it if necessary:

[code]#!/bin/bash

cat /dev/null > ./list
while read line
do
case $line in
host*) echo -n $line | sed ‘s/host_name //g’ >> list;;
alias*) echo -n $line | sed ‘s/alias /, /g’ >> list;;
address*) echo $line | sed ‘s/address /, /g’ >> list && echo “” >> list;;
esac
done < ./hosts.cfg[/code]

You have to modify the input file if you named it somehow else then hosts.cfg, and the script will output the data you need in list file. Of course you have to run the script from the folder where your hosts.cfg reside, or copy hosts.cfg to the folder containing this script.

And don’t get used to such solution of me writing the scripts for you :slight_smile:


#3

Thanks for the reply and script to get me going. I had started to piece something together and had half of it but was having difficulty in figuring out how to get the third piece of information for each host. I was going down of a PHP or Perl script.

I’ll post what I put together in the end. I have to do the shell script now, then run that output through the tr command to strip out the ^M character after each piece of information. Working on getting it all handled at once in the script.

I just was curious if there was already an existing script before I spent more time on figuring one out. It’s been a long while since I’ve done shell programming type stuff.


#4

This is what I ended up with to get what I needed, thanks for the help. It uses first command line argument for input file and second for output file.


exec 10<$1
let count=0

while read devicename <&10; do

# Remove ^M from line read
line=`echo "$devicename" | tr -d '(control-V)(control-M)'`

case $line in                                                                   
        host*) printf "$line" | gawk '{ printf $2}'  >> $2 && printf "," >>$2;; 
        alias*) printf "$line" | gawk '{ printf $2}'  >> $2 && printf "," >>$2;;
        address*) printf "$line" | gawk '{ printf $2}'  >> $2 && printf "\n" >> $2;;
    esac                                                                        
done
# close file
exec 10>&-