Skip to content

Instantly share code, notes, and snippets.

@phrawzty
Created March 1, 2011 14:40
Show Gist options
  • Save phrawzty/849214 to your computer and use it in GitHub Desktop.
Save phrawzty/849214 to your computer and use it in GitHub Desktop.
A simple Nagios plugin that makes an HTTP request and interprets a JSON response; implemented in Ruby - because why not? This is really more of a proof of concept than something super useful, so ymmv. ;)
#!/usr/bin/ruby1.9.1
# Nagios plugin that looks for some JSON or summat.
require 'json'
require 'net/http'
require 'uri'
require 'optparse'
@options = {}
# display verbose output (if being run by a human for example)
def say msg
if @options[:verbose] == true
puts msg
end
end
def do_exit code
if @options[:verbose] == true
exit 3
else
exit code
end
end
# Parse cli args
optparse = OptionParser.new do |opts|
opts.banner = 'Usage: %s [-V] -u <URI> -n <name> -v <value>' % [$0]
opts.on('-h', '--help', 'Help info') do
puts opts
do_exit(3)
end
@options[:uri] = nil
opts.on('-u', '--uri URI', 'Target URI') do |uri|
@options[:uri] = uri
end
@options[:name] = nil
opts.on('-n', '--name NAME', 'Name of the variable') do |name|
@options[:name] = name
end
@options[:value] = nil
opts.on('-v', '--value VALUE', 'Value of the variable') do |value|
@options[:value] = value
end
@options[:verbose] = false
opts.on('-V', '--verbose', 'Human output') do
@options[:verbose] = true
end
end
# Get those args!
optparse.parse!
error_msg = []
if not @options[:uri] then
error_msg.push('Need to specify the URI.')
end
if not @options[:name] then
error_msg.push('Need to specify the name of the variable.')
end
if not @options[:value] then
error_msg.push('Need to specify a value for the variable.')
end
if error_msg.count > 0 then
puts 'Aborting for the following reason(s):'
error_msg.each do |msg|
puts msg
end
puts "$ %s --help for more information." % [$0]
do_exit(3)
end
uri = URI.parse(@options[:uri])
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
# We must get a proper response
if not response.code.to_i == 200 then
puts 'CRIT: Received HTTP code %s instead of 200.' % [response.code]
do_exit(2)
end
say("---\nRESPONSE: %s\n---" % [response.body])
json = JSON.parse response.body
json.each do |name,value|
if name == @options[:name] then
if value.to_s == @options[:value].to_s then
puts 'OK: %s => %s' % [name, value]
do_exit(0)
else
puts 'CRIT: %s => %s' % [name, value]
do_exit(2)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment