quick script to pull load average

Posted by scottk on July 24, 2008 in Sysadmin |

Needed to code up something rather quickly today to monitor load average on our servers and send a notification. I should look into getting OpenNMS to do this, but it only took a few tweaks to an existing program to create this.  Before hand you need nmap running and creating the servers.txt and SNMP setup on the servers.

#!/usr/bin/perl -w

use strict;
use Net::SNMP;
use MIME::Lite;
use POSIX;

my %servers;

my %skip_list = (
  '10.168.0.1'   => 'Pix',
  '10.168.1.101' => 'Power Strip',
  '10.168.1.102' => 'Power Strip',
  '10.168.5.100' => 'Windows Backup Server aka The Sux',
  );

my $date = strftime('%Y-%m-%d',localtime(time));

open(FILE,"<","servers.txt");
while (<FILE>) {
  my $line = $_;
  my ($ip,$hostname) = $line =~ /^Host\: (\d+\.\d+\.\d+\.\d+) \((.*?)\)/;
  next if ( !$ip || !$hostname );
  #print "$ip $hostname\n";
  $servers{$ip} = $hostname;
  }
close(FILE);

my $output;
my $urgent;
my $watch;
foreach my $server ( sort keys %servers ) {
  #print "QUERY SERVER $server\n";
  next if ( $skip_list{$server} );
  eval {
    my ($session, $error) = Net::SNMP->session(
       -version   => 'snmpv2c',
       -hostname  => $server || 'localhost',
       -community => 'public',
       -port      => 161
       );

    if (!defined($session)) {
      printf("ERROR: %s.\n", $error);
      next;
      }

    my $loadAverage = '1.3.6.1.4.1.2021.10.1.5.2';

    my $result = $session->get_request(
      -varbindlist => [$loadAverage]
      );

    if (!defined($result)) {
      printf("ERROR: %s.\n", $session->error);
      $session->close;
      next;
      }

    my $load = sprintf( '%.2f', ( $result->{$loadAverage} / 100 ) );
    #print "Load $server\t$load\n";

    $session->close;

    if ( $load > 5 ) {
      $watch .= "$servers{$server}($server) LOAD: $load\n\n";
      }
    }
  }

if ($watch && $watch ne '') {
  $watch .= "\n\nSYSRPTID-007\n\n";
  my $msg = MIME::Lite->new(
         From    =>      'me@host.com',
         To      =>      'me@host.com',
         Subject =>      "[SYS Report] Load Check $date",
         Type    =>      'text/plain',
         Sender  =>      'me@host.com',
         Data    =>      "$watch"
         );
  MIME::Lite->send('smtp','outbound.host.com', Timeout=>60, Hello => 'outbound.host.com');
  $msg->send();
  #print "$watch\n";
  }
exit;

Tags: ,

Copyright © 2006-2024 SimpIT.com All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.