Thursday, April 10, 2014

Perl Script: basic SNMP trap-handler.pl

#!/usr/local/bin/perl -w
#
# Reference:
#   http://net-snmp.sourceforge.net/wiki/index.php/TUT:Configuring_snmptrapd
#
use strict;

## set slurp mode to read the input
# $/ = undef;

# First line in the input is the hostname
my $traphost = ;
chomp $traphost;

# Second line in the input is the IP address port details
# which aren't totally useful so they aren't jammed into
# the output
my $trapip   = ;
chomp $trapip;

my $traptext = '';

# Take the rest of the input and chop it up into pairs
# of "xzy = 1234" as usually the output is a set of pairs
# with the OID and the value of the OID
while () {
    # skip over the uptime, it's just noise
    next if (m!DISMAN-EVENT-MIB::sysUpTimeInstance!soig);

    # this is noise too, it is in every trap
    next if (m!SNMPv2-MIB::snmpTrapOID.0.*SNMPv2-SMI::enterprises.3224.0.200!soig);

    if (m!^(\S+)\s+(.*)$!oig) {
        $traptext .= "$1 = $2\n";
    } else {
        $traptext .= $_;
    }
}

# Turn new lines in a "," as we want all the syslog output to go
# into one line
$traptext =~ s/\n/, /mg;

# chop off the last "," coz it looks stoopid
$traptext =~ s/,+\s*$//g;

system("/usr/bin/logger -t trap-handler '$traphost: $traptext'");

No comments:

Post a Comment