#!/usr/bin/perl -w ### ### Listen for SNMP traps, decode and print them ### Simple example for a trap listener program. ### ### To make this useful, you should probably add some filtering ### capabilities and trap-specific pretty-printing. ### package main; use strict; use SNMP_Session "0.60"; use BER; use Socket; ### Forward declarations sub print_trap ($$); my $port = 162; my $session = SNMPv1_Session->open_trap_session ($port) or die "couldn't open trap session"; my ($trap, $sender, $sender_port); while (($trap, $sender, $sender_port) = $session->receive_trap ()) { print STDERR "received trap from [".inet_ntoa ($sender)."].".$sender_port."\n"; print_trap ($session, $trap); } 1; sub print_trap ($$) { my ($this, $trap) = @_; my ($encoded_pair, $oid, $value); my ($community, $ent, $agent, $gen, $spec, $dt, $bindings) = $this->decode_trap_request ($trap); my ($binding, $prefix); if (defined $community) { print " community: ".$community."\n"; if (defined $ent) { ## SNMPv1 Trap print " enterprise: ".BER::pretty_oid ($ent)."\n"; print " agent addr: ".inet_ntoa ($agent)."\n"; print " generic ID: $gen\n"; print " specific ID: $spec\n"; print " uptime: ".BER::pretty_uptime_value ($dt)."\n"; } ## Otherwise we have an SNMPv1 Trap which basically just ## consists of bindings. ## $prefix = " bindings: "; while ($bindings) { ($binding,$bindings) = decode_sequence ($bindings); ($oid,$value) = decode_by_template ($binding, "%O%@"); print $prefix.BER::pretty_oid ($oid)." => ".pretty_print ($value)."\n"; $prefix = " "; } } else { warn "decoding trap request failed:\n".$SNMP_Session::errmsg; } }