1#!/usr/bin/perl 2 3# This is a snmptrapd handler script to convert snmp traps into email 4# messages. 5 6# Usage: 7# Put a line like the following in your snmptrapd.conf file: 8# traphandle TRAPOID|default /usr/local/bin/traptoemail [-f FROM] [-s SMTPSERVER]b ADDRESSES 9# FROM defaults to "root" 10# SMTPSERVER defaults to "localhost" 11 12use Net::SMTP; 13use Getopt::Std; 14use POSIX qw(strftime); 15 16$opts{'s'} = "localhost"; 17$opts{'f'} = 'root@' . `hostname`; 18chomp($opts{'f'}); 19getopts("hs:f:", \%opts); 20 21if ($opts{'h'}) { 22 print " 23traptoemail [-s smtpserver] [-f fromaddress] toaddress [...] 24 25 traptoemail shouldn't be called interatively by a user. It is 26 designed to be called as an snmptrapd extension via a \"traphandle\" 27 directive in the snmptrapd.conf file. See the snmptrapd.conf file for 28 details. 29 30 Options: 31 -s smtpserver Sets the smtpserver for where to send the mail through. 32 -f fromaddress Sets the email address to be used on the From: line. 33 toaddress Where you want the email sent to. 34 35"; 36 exit; 37} 38 39die "no recepients to send mail to" if ($#ARGV < 0); 40 41# process the trap: 42$hostname = <STDIN>; 43chomp($hostname); 44$ipaddress = <STDIN>; 45chomp($ipaddress); 46 47$maxlen = 0; 48while(<STDIN>) { 49 ($oid, $value) = /([^\s]+)\s+(.*)/; 50 push @oids, $oid; 51 push @values, $value; 52 $maxlen = (length($oid) > $maxlen) ? length($oid) : $maxlen; 53} 54$maxlen = 60 if ($maxlen > 60); 55$formatstr = "%" . $maxlen . "s %s\n"; 56 57die "illegal trap" if ($#oids < 1); 58 59# send the message 60$message = Net::SMTP->new($opts{'s'}) || die "can't talk to server $opts{'s'}\n"; 61$message->mail($opts{'f'}); 62$message->to(@ARGV) || die "failed to send to the recepients ",join(",",@ARGV),": $!"; 63$message->data(); 64$message->datasend("To: " . join(", ",@ARGV) . "\n"); 65$message->datasend("From: $opts{f}\n"); 66$message->datasend("Date: ".strftime("%a, %e %b %Y %X %z", localtime())."\n"); 67$message->datasend("Subject: trap received from $hostname: $values[1]\n"); 68$message->datasend("\n"); 69$message->datasend("Host: $hostname ($ipaddress)\n"); 70for($i = 0; $i <= $#oids; $i++) { 71 $message->datasend(sprintf($formatstr, $oids[$i], $values[$i])); 72} 73$message->dataend(); 74$message->quit; 75