Nagios Plugin to Check Memory

After a search for a check_memory plugin for Nagios turned up only a Korn shell script, I quickly wrote the following in Ruby for Linux, which I hereby release into the public domain.   Why?  All my servers have Ruby, but not Korn shell.

#!/usr/bin/env ruby

require 'optparse'

options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [OPTIONS]"

  opts.on('-w', '--warn PCT', 'Warn if memory usage goes over PCT') do |val|
    options[:warn_pct] = val.to_i
  end

  opts.on('-c', '--crit PCT', 'Critical if memory usage goes over PCT') do |val|
    options[:crit_pct] = val.to_i
  end

  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
end
optparse.parse!

unless options[:crit_pct] && options[:warn_pct]
  puts optparse.help
  exit
end

# Get the stats from /proc
mem = File.readlines("/proc/meminfo").inject({}) {|m,x| k,v = x.split(/:?\s+/); m[k] = v.to_i; m}
free = mem['MemFree'] + mem['Buffers'] + mem['Cached']
total = mem['MemTotal']
used = total - free
pct_used = used * 100 / total

if pct_used > options[:crit_pct]
  puts "MEMORY CRTIICAL - #{pct_used}% used"
  exit 2
elsif pct_used > options[:warn_pct]
  puts "MEMORY WARNING -  #{pct_used}% used"
  exit 1
else
  puts "MEMORY OK - #{pct_used}% used"
end

This goes in /usr/lib/nagios/plugins/check_memory . You can add it to nrpe.cfg like so:

command[check_memory]=/usr/lib/nagios/plugins/check_memory  -w 75 -c 85

Update: Found a shell script here

This entry was posted in sysadmin. Bookmark the permalink.

2 Responses to Nagios Plugin to Check Memory

  1. Paul Charles Leddy says:

    Some html coding stuck into the code. I fix them on my side.

    Been looking for this for a while, thanks.

  2. Clif Smith says:

    Thanks for this!

Leave a Reply

Your email address will not be published. Required fields are marked *