Nagiosの設定ファイルをEXCEL一覧表示するためにCSVに落とすスクリプトを書いたのでメモしておきます。
#!/bin/sh exec ruby -S -x $0 "$@" #! ruby delimiter=',' file = File.open(ARGV[0]) configs = [] values = [] keys = [] file.each_line do |line| next if /^\s*$/ =~ line next if /^#/ =~ line if 'define host{' == line.strip next elsif '}' == line.strip configs.push(values) values = [] else key, value = line.strip.match(/^([^\s#;]*)\s*([^#;]*).*$/)[1..2] keys.push(key) unless keys.include?(key) values.push(key => value.gsub(/,/,"|")) end end puts keys.join(delimiter) configs.each do |cfg| line = [] cfg.each do |item| key_num = keys.index(item.keys.join) line[key_num] = item.values.join end puts line.join(delimiter) end
動かす
設定ファイル例としてこちらのサンプルを使ってみます。
################################################################################ # Sample object config file for Nagios @VERSION@ # # Read the documentation for more information on this configuration file. I've # provided some comments here, but things may not be so clear without further # explanation, so make sure to read the HTML documentation! # # Last Modified: 03-10-2002 # ################################################################################ ################################################################################ # HOST DEFINITIONS # # SYNTAX: # ################################################################################ # Generic host definition template define host{ name generic-host ; The name of this host template - referenced in other host definitions, used for template recursion/resolution notifications_enabled 1 ; Host notifications are enabled event_handler_enabled 1 ; Host event handler is enabled flap_detection_enabled 1 ; Flap detection is enabled process_perf_data 1 ; Process performance data retain_status_information 1 ; Retain status information across program restarts retain_nonstatus_information 1 ; Retain non-status information across program restarts register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE! } # 'novell1' host definition define host{ use generic-host ; Name of host template to use host_name novell1 alias Novell Server #1 address 192.168.1.2 check_command check-host-alive max_check_attempts 10 notification_interval 120 notification_period 24x7 notification_options d,u,r } # 'novell2' host definition define host{ use generic-host ; Name of host template to use host_name novell2 alias Novell Server #2 address 192.168.1.3 check_command check-host-alive max_check_attempts 10 notification_interval 120 notification_period 24x7 notification_options d,u,r } (以下略)
実行
実行してみます。
$ ./convert_hostscfg_to_csv.rb hosts_sample.cfg > hosts_sample.csv
rubyのshebang
本筋では無いですが、rubyのshebangって以下をよく見ますが、
#! /usr/bin/env ruby
ここを参考にして、 qiita.com
このように書いています。
#! /bin/sh exec ruby -S -x "$0" "$@" #! ruby