#!/usr/bin/perl -w
#by barlow修改
#use strict;
use Getopt::Std;
use vars qw($opt_c $opt_f $opt_u $opt_w
$free_memory $used_memory $total_memory
$crit_level $warn_level
%exit_codes @memlist
$percent $fmt_pct
$verb_err $command_line);
# Predefined exit codes for Nagios
%exit_codes = ('UNKNOWN' ,-1,
'OK' , 0,
'WARNING' , 1,
'CRITICAL', 2,);
#
$verb_err = 0;
#注意命令需要全路径,且该命令需要root权限
$command_line = `/usr/sbin/swapinfo | tail -1 | awk '{print \$3,\$4}'`;
chomp $command_line;
@memlist = split(/ /, $command_line);
# Define the calculating scalars
$used_memory = $memlist[0];
$free_memory = $memlist[1];
$total_memory = $used_memory + $free_memory;
# Get the options
if ($#ARGV le 0)
{
&usage;
}
else
{
getopts('c:fuw:');
}
# Shortcircuit the switches
if (!$opt_w or $opt_w == 0 or !$opt_c or $opt_c == 0)
{
print "*** You must define WARN and CRITICAL levels!" if ($verb_err);
&usage;
}
elsif (!$opt_f and !$opt_u)
{
print "*** You must select to monitor either USED or FREE memory!" if ($verb_err);
&usage;
}
# Check if levels are sane
if ($opt_w <= $opt_c and $opt_f)
{
print "*** WARN level must not be less than CRITICAL when checking FREE memory!" if ($verb_err);
&usage;
}
elsif ($opt_w >= $opt_c and $opt_u)
{
print "*** WARN level must not be greater than CRITICAL when checking USED memory!" if ($verb_err);
&usage;
}
$warn_level = $opt_w;
$crit_level = $opt_c;
if ($opt_f)
{
$percent = $free_memory / $total_memory * 100;
$fmt_pct = sprintf "%.1f", $percent;
if ($percent <= $crit_level)
{
print "Memory CRITICAL -FREE $fmt_pct% (FREE:$free_memory kB TOTAL:$total_memory kB)\n";
exit $exit_codes{'CRITICAL'};
}
elsif ($percent <= $warn_level)
{
print "Memory WARNING -FREE $fmt_pct% (FREE:$free_memory kB TOTAL:$total_memory kB)\n";
exit $exit_codes{'WARNING'};
}
else
{
print "Memory OK -FREE $fmt_pct% (FREE:$free_memory kB TOTAL:$total_memory kB)\n";
exit $exit_codes{'OK'};
}
}
elsif ($opt_u)
{
$percent = $used_memory / $total_memory * 100;
$fmt_pct = sprintf "%.1f", $percent;
if ($percent >= $crit_level)
{
print "Memory CRITICAL -USED $fmt_pct% (USED:$used_memory kB TOTAL:$total_memory kB)\n";
exit $exit_codes{'CRITICAL'};
}
elsif ($percent >= $warn_level)
{
print "Memory WARNING -USED $fmt_pct% (USED:$used_memory kB TOTAL:$total_memory kB)\n";
exit $exit_codes{'WARNING'};
}
else
{
print "Memory OK -USED $fmt_pct% (USED:$used_memory kB TOTAL:$total_memory kB)\n";
exit $exit_codes{'OK'};
}
}
#打印帮助
sub usage()
{
print "\ncheck_mem.pl - Nagios Plugin\n\n";
print "usage:\n";
print " check_mem.pl - -w -c \n\n";
print "options:\n";
print " -f Check FREE memory\n";
print " -u Check USED memory\n";
print " -w PERCENT Percent free/used when to warn\n";
print " -c PERCENT Percent free/used when critical\n";
exit $exit_codes{'UNKNOWN'};
}