#!/usr/bin/perl

#
# check_conn - A nagios plugin to check the number of simultanious connections 
#              on a given port number
#              

#
# Copyright (C) 2008 John Sennesael
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
use strict ;
use Switch ;

# globals ---------------------------------------------------------------------

my $warn = 120 ;
my $critical = 200 ;
my $port = 80 ;

# subroutines -----------------------------------------------------------------

sub os
{
  my $os = `uname`;
  my $result = "unknown";
  $os = lc($os);
  if ($os =~ /bsd/)
  {
    $result = "bsd"
  }
  elsif ($os =~ /linux/)
  {
    $result = "linux"
  }
  else
  {
    die ("Operating system not supported.");
  }
  return $result;
}

sub check
{
  my $result = 0 ;
  my $command = "";
  if (os eq 'linux')
  {
    $command = "netstat -ant | grep ESTABLISHED | awk -F ' ' '{print \$4}' | egrep '???.???.???.???:" . $port . "' | wc -l" ;
  }
  elsif (os eq 'bsd')
  {
    $command = "netstat -ant | grep ESTABLISHED | awk -F ' ' '{print \$4}' | egrep '???.???.???.???." . $port . "' | wc -l" ; 
  }
  my $val = `$command` ;
  chomp ($val) ;
  if ($val ne "")
  {
    $result = $val ;
  }
  return $result ;
}

# main program ----------------------------------------------------------------

# parse args
my $n = 0 ;
foreach my $arg (@ARGV)
{
  my $ARGC = @ARGV;
  switch ($arg)
  {
    case "-c" 
    {
      if ( $ARGC < ($n+1) )
      {
        die("No value specified for -c.") ;
      }
      $critical = $ARGV[$n+1] ;
    }
    case "-w" 
    {
      if ( $ARGC < ($n+1) )
      {
        die("No value specified for -w.") ;
      }
      $warn = $ARGV[$n+1] ;
    }
    case "-p"
    {
      if ( $ARGC < ($n+1) )
      {
        die("No value specified for -p.") ;
      }
      $port = $ARGV[$n+1] ;
    }
  }
  $n += 1;
}

my $val = check ;
my $status = "OK" ;

if ( $val >= $warn )
{
  $status = "WARN" ;
}

if ( $val >= $critical )
{
  $status = "CRITICAL" ;
}

print "CONN " . $status . " - connections: " . $val . "\n";
