RubyからNagiosを操作するnagiosharderが良い感じ

手元のRubyスクリプトからNagiosの操作をしたければ、cgiを叩けばいいのですが、このGem使えば簡単に書けます。

github.com

スクリプト

例えば、あるホストの全サービスの通知を開始・停止したい場合のスクリプトです。

#!/bin/sh
exec ruby -S -x $0 "$@"
#! ruby
require 'nagiosharder'

mode=ARGV[0]
if ARGV.length < 2 || (mode != 'start' && mode != 'stop')
  p 'usage: $0 <start|stop> hosts1 host2 ...'   
  exit
end
hosts = ARGV[1..-1]

cgi = 'http://nagios.local/nagios/cgi-bin/'
user = 'nagiosadmin'
pass= 'p@ssw0rd'
version = 3
time_format = 'us' 
verify_ssl = false
site = NagiosHarder::Site.new(cgi, user, pass, version, time_format, verify_ssl)

hosts.each do |host| 
  site.host_status(host).map do |k,v| 
    v.service 
  end.each do |svc|
    site.disable_service_notifications(host,svc) if mode=='stop'
    site.enable_service_notifications(host,svc) if mode=='start'
    p "#{mode} nagios notifications for host:#{host} service:#{svc}"
  end
end

コマンド実行

コマンドで直接実行することも可能です。

ヘルプ

$ nagiosharder
Usage: nagiosharder [options] [command]
    -h, --help
    -c, --config [/path/to/file]     YAML config file [optional, but recommended]
    -u, --user USER                  Nagios user
    -p, --password PASSWORD          Nagios password
    -n, --nagios_url URL             Nagios cgi url
    -v, --version [3]                Nagios version (2 or 3, defaults to 3)
    -t, --time [us|euro]             Nagios time format

コマンド実行例

$ nagiosharder -n http://nagios.local/nagios/cgi-bin/ -u nagiosadmin -p p@ssw0rd -t us -v 3 status target
+-------------------------------+--------+------------------------------------------+
| Service                       | Status | Details                                  |
+-------------------------------+--------+------------------------------------------+
| target/Current Load       |     OK | OK - load average: 1.58, 1.40, 1.89      |
| target/Disk                      |     OK | DISK OK - free space: / 8417 MB (31%     |
         |                               |        | inode=79%):                              |
| target/Memory Usage       |     OK | Memory OK - 46.2% (3726556 kB) free      |
| target/PING               |     OK | PING OK - Packet loss = 0%, RTA = 0.05   |
+-------------------------------+--------+------------------------------------------+