#!/usr/bin/perl # check_cmusage version 1.0, 17/7/2013 # Written by Caofaguo # This plugin is for LINUX edition. Computing cpu and mem usage. # You need basic perl package to run this plugin. use warnings; use strict; use Getopt::Std; my $STATE_OK = 0; my $STATE_WARNING = 1; my $STATE_CRITICAL = 2; my (@paraw,@parac,$cpu_w,$mem_w,$cpu_c,$mem_c); my $USAGE = " $0 <-w cpu,memory> <-c cpu,memory> -c # CPU,Memory Warning value; -w # CPU,Memory Critical value; For example: check_cmusage -w 90,90 -c 95,95 "; my %opts; unless (getopts('c:w:', \%opts)) { print $USAGE; exit 1; } unless ((defined $opts{'c'}) && (defined $opts{'w'})) { print $USAGE; exit 1; } if (defined $opts{'w'}) { @paraw = split(/,/,$opts{'w'}); $cpu_w = $paraw[0]; $mem_w = $paraw[1]; } if (defined $opts{'c'}) { @parac = split(/,/,$opts{'c'}); $cpu_c = $parac[0]; $mem_c = $parac[1]; } ## The CPU usage list my $SLEEPTIME=5; my ($user1,$nice1,$sys1,$idle1,$iowait1,$irq1,$softirq1); my ($user2,$nice2,$sys2,$idle2,$iowait2,$irq2,$softirq2); open (JIFF, "/proc/stat") || die "Can't open /proc/stat file!\n"; while(my $line=){ if($line=~/^cpu\s+(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+).*/){ ($user1,$nice1,$sys1,$idle1,$iowait1,$irq1,$softirq1)=($1,$2,$3,$4,$5,$6,$7); } } close (JIFF); sleep $SLEEPTIME; open (JIFF, "/proc/stat") || die "Can't open /proc/stat file!\n"; while(my $line=){ if($line=~/^cpu\s+(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+).*/){ ($user2,$nice2,$sys2,$idle2,$iowait2,$irq2,$softirq2)=($1,$2,$3,$4,$5,$6,$7); } } close (JIFF); my $JIFF_1=$user1+$nice1+$sys1+$idle1+$iowait1+$irq1+$softirq1; my $JIFF_2=$user2+$nice2+$sys2+$idle2+$iowait2+$irq2+$softirq2; my $cpu_usage=100-($idle1-$idle2)/($JIFF_1-$JIFF_2)*100; ## The Memory usage list my ($memtotal,$memfree,$buffers,$cached,$mem_usage); my $filename='/proc/meminfo'; open my $FILE, '<', $filename or die "Can't open config file:$!"; while (my $line=<$FILE>) { if($line=~/^MemTotal:\s+(\d+)\s/){ $memtotal = $1; }elsif($line=~/^MemFree:\s+(\d+)\s/){ $memfree = $1; }elsif($line=~/^Buffers:\s+(\d+)\s/){ $buffers = $1; }elsif($line=~/^Cached:\s+(\d+)\s/){ $cached = $1; } } $mem_usage = ($memtotal-$memfree-$buffers-$cached)/$memtotal*100; if ($cpu_usage < $cpu_w && $mem_usage < $mem_w) { printf "OK - CPU Usage:%1.2f%% Mem Usage:%1.2f%% |cusage=%1.2f%%;$cpu_w;$cpu_c;0; musage=%1.2f%%;$mem_w;$mem_c;0;\n",$cpu_usage,$mem_usage,$cpu_usage,$mem_usage; exit $STATE_OK; }elsif ($cpu_usage < $cpu_c && $mem_usage < $mem_c){ printf "WARNING - CPU Usage:%1.2f%% Mem Usage:%1.2f%% |cusage=%1.2f%%;$cpu_w;$cpu_c;0; musage=%1.2f%%;$mem_w;$mem_c;0;\n",$cpu_usage,$mem_usage,$cpu_usage,$mem_usage; exit $STATE_WARNING; }else { printf "CRITICAL - CPU Usage:%1.2f%% Mem Usage:%1.2f%% |cusage=%1.2f%%;$cpu_w;$cpu_c;0; musage=%1.2f%%;$mem_w;$mem_c;0;\n",$cpu_usage,$mem_usage,$cpu_usage,$mem_usage; exit $STATE_CRITICAL; }