Trap handlers can be written in any language you prefer, but for this document we'll use PERL.
At least 3 lines of input will be handed to your trap handler via STDIN, in addition to any arguments you passed to it in your snmptrapd.conf. The first line of input is the hostname (if it can not be resolved it will use the IP address). The second line of input is the IP address. All remaining lines of input will be the data passed by the trap.
Traps will pass in a list of OIDs with their values (elsewhere called a VARBIND or VarList), one per line. It is best to handle this list by simply pushing the values onto an array for later processing.
#!/usr/bin/perl # A simple trap handler my $TRAP_FILE = "/var/snmp/traps.all.log"; my $host = <STDIN>; # Read the Hostname - First line of input from STDIN chomp($host); my $ip = <STDIN>; # Read the IP - Second line of input chomp($ip); while(<STDIN>) { chomp($_); push(@vars,$_); } open(TRAPFILE, ">> $TRAP_FILE"); $date = `date`; chomp($date); print(TRAPFILE "New trap received: $date for $OID\n\nHOST: $host\nIP: $ip\n"); foreach(@vars) { print(TRAPFILE "TRAP: $_\n"); } print(TRAPFILE "\n----------\n"); close(TRAPFILE);
Here is an example of a trap that was logged using the trap handler above:
New trap received: Wed Oct 27 16:32:18 PDT 2004 for HOST: 10.100.2.248 IP: 10.100.2.248 TRAP: RFC1213-MIB::sysUpTime.0 48:17:24:09.31 TRAP: SNMPv2-MIB::snmpTrapOID.0 IF-MIB::linkUp TRAP: RFC1213-MIB::ifIndex 5017 TRAP: RFC1213-MIB::ifAdminStatus up TRAP: RFC1213-MIB::ifOperStatus up ----------
Basic trap handlers like this one are a useful starting point for building more complex trap handlers. By parsing the incoming traps and also using arguments passed to the handler based on the trap OID in the configuration file you can build complex trap handling routines to report problems, investigate them, or even respond to them if you have a strong stomach. Because of the large amount of parsing done when processing traps it is recommended that languages with strong string manipulation abilities such as PERL, Python or Ruby are used.
You can find an example of a more complicated trap handler here:
http://www.cuddletech.com/tools/extreme_traphandle.html