Code

New or revised plugin in /contrib
[nagiosplug.git] / contrib / check_email_loop.pl
1 #!/usr/bin/perl 
2 #
3 # (c)2000 Benjamin Schmid, blueshift@gmx.net (emergency use only ;-)
4 # Copyleft by GNU GPL
5 #
6 #
7 # check_email_loop Nagios Plugin
8 #
9 # This script sends a mail with a specific id in the subject via
10 # an given smtp-server to a given email-adress. When the script
11 # is run again, it checks for this Email (with its unique id) on
12 # a given pop3 account and send another mail.
13
14 #
15 # Example: check_email_loop.pl -poph=mypop -popu=user -pa=password
16 #          -smtph=mailer -from=returnadress@yoursite.com
17 #          -to=remaileradress@friend.com -pendc=2 -lostc=0
18 #
19 # This example will send eacht time this check is executed a new
20 # mail to remaileradress@friend.com using the SMTP-Host mailer.
21 # Then it looks for any back-forwarded mails in the POP3 host
22 # mypop. In this Configuration CRITICAL state will be reached if  
23 # more than 2 Mails are pending (meaning that they did not came 
24 # back till now) or if a mails got lost (meaning a mail, that was
25 # send later came back prior to another mail).
26
27 # Michael Markstaller, mm@elabnet.de various changes/additions
28 # MM 021003: fixed some unquoted strings
29 # MM 021116: fixed/added pendwarn/lostwarn
30 # MM 030515: added deleting of orphaned check-emails 
31 #                                         changed to use "top" instead of get to minimize traffic (required changing match-string from "Subject: Email-ping [" to "Email-Ping ["
33 use Net::POP3;
34 use Net::SMTP;
35 use strict;
36 use Getopt::Long;
37 &Getopt::Long::config('auto_abbrev');
39 # ----------------------------------------
41 my $TIMEOUT = 120;
42 my %ERRORS = ('UNKNOWN' , '-1',
43               'OK' , '0',
44               'WARNING', '1',
45               'CRITICAL', '2');
47 my $state = "UNKNOWN";
48 my ($sender,$receiver, $pophost, $popuser, $poppasswd, $smtphost,$keeporphaned);
49 my ($poptimeout,$smtptimeout,$pinginterval,$maxmsg)=(60,60,5,50);
50 my ($lostwarn, $lostcrit,$pendwarn, $pendcrit);
52 # Internal Vars
53 my ($pop,$msgcount,@msglines,$statinfo,@messageids,$newestid);
54 my ($matchcount,$statfile) = (0,"check_email_loop.stat");
56 # Subs declaration
57 sub usage;
58 sub messagematchs;
59 sub nsexit;
61 # Just in case of problems, let's not hang Nagios
62 $SIG{'ALRM'} = sub {
63      print ("ERROR: $0 Time-Out $TIMEOUT s \n");
64      exit $ERRORS{"UNKNOWN"};
65 };
66 alarm($TIMEOUT);
69 # Evaluate Command Line Parameters
70 my $status = GetOptions(
71                         "from=s",\$sender,
72                         "to=s",\$receiver,
73                         "pophost=s",\$pophost,
74                         "popuser=s",\$popuser,
75                         "passwd=s",\$poppasswd,
76                         "poptimeout=i",\$poptimeout,
77                         "smtphost=s",\$smtphost,
78                         "smtptimeout=i",\$smtptimeout,
79                         "statfile=s",\$statfile,
80                         "interval=i",\$pinginterval,
81                         "lostwarn=i",\$lostwarn,
82                         "lostcrit=i",\$lostcrit,
83                         "pendwarn=i",\$pendwarn,
84                         "pendcrit=i",\$pendcrit,
85                         "maxmsg=i",\$maxmsg,
86                         "keeporphaned=s",\$keeporphaned,
87                         );
88 usage() if ($status == 0 || ! ($pophost && $popuser && $poppasswd &&
89         $smtphost && $receiver && $sender ));
91 # Try to read the ids of the last send emails out of statfile
92 if (open STATF, "$statfile") {
93   @messageids = <STATF>;
94   chomp @messageids;
95   close STATF;
96 }
98 # Try to open statfile for writing 
99 if (!open STATF, ">$statfile") {
100   nsexit("Failed to open mail-ID database $statfile for writing",'CRITICAL');
103 # Ok - check if it's time to release another mail
105 # ...
107 # creating new serial id
108 my $serial = time();
109 $serial = "ID#" . $serial . "#$$";
111 # sending new ping email
112 my $smtp = Net::SMTP->new($smtphost,Timeout=>$smtptimeout) 
113   || nsexit("SMTP connect timeout ($smtptimeout s)",'CRITICAL');
114 ($smtp->mail($sender) &&
115  $smtp->to($receiver) &&
116  $smtp->data() &&
117  $smtp->datasend("To: $receiver\nSubject: E-Mail Ping [$serial]\n\n".
118                  "This is a automatically sended E-Mail.\n".
119                  "It ist not intended for human reader.\n\n".
120                  "Serial No: $serial\n") &&
121  $smtp->dataend() &&
122  $smtp->quit
123  ) || nsexit("Error delivering message",'CRITICAL');
125 # no the interessting part: let's if they are receiving ;-)
127 $pop = Net::POP3->new( $pophost, 
128                  Timeout=>$poptimeout) 
129        || nsexit("POP3 connect timeout (>$poptimeout s, host: $pophost)",'CRITICAL');
131 $msgcount=$pop->login($popuser,$poppasswd);
133 $statinfo="$msgcount mails on POP3";
135 nsexit("POP3 login failed (user:$popuser)",'CRITICAL') if (!defined($msgcount));
137 # Check if more than maxmsg mails in pop3-box
138 nsexit(">$maxmsg Mails ($msgcount Mails on POP3); Please delete !",'WARNING') if ($msgcount > $maxmsg);
140 # Count messages, that we are looking 4:
141 while ($msgcount > 0) {
142   @msglines = @{$pop->top($msgcount,1)};
143   for (my $i=0; $i < scalar @messageids; $i++) {
144     if (messagematchsid(\@msglines,$messageids[$i])) { 
145       $matchcount++;
146       # newest received mail than the others, ok remeber id.
147       $newestid = $messageids[$i] if ($messageids[$i] > $newestid || !defined $newestid);
148       $pop->delete($msgcount);  # remove E-Mail from POP3 server
149       splice @messageids, $i, 1;# remove id from List
150           last;                     # stop looking in list
151         } 
152   } 
153         # Delete orphaned Email-ping msg
154         my @msgsubject = grep /^Subject/, @msglines;
155         chomp @msgsubject;
156         # Scan Subject if email is an Email-Ping. In fact we match and delete also successfully retrieved messages here again.
157         if (!defined $keeporphaned && $msgsubject[0] =~ /E-Mail Ping \[/) {
158             $pop->delete($msgcount);  # remove E-Mail from POP3 server
159         }
161         $msgcount--;
164 $pop->quit();  # necessary for pop3 deletion!
166 # traverse through the message list and mark the lost mails
167 # that mean mails that are older than the last received mail.
168 if (defined $newestid) {
169   $newestid =~ /\#(\d+)\#/;
170   $newestid = $1;
171   for (my $i=0; $i < scalar @messageids; $i++) {
172     $messageids[$i] =~ /\#(\d+)\#/;
173     my $akid = $1;
174     if ($akid < $newestid) {
175       $messageids[$i] =~ s/^ID/LI/; # mark lost
176     }
177   }
180 # Write list to id-Database
181 foreach my $id (@messageids) {
182   print STATF  "$id\n";
184 print STATF "$serial\n";     # remember send mail of this session
185 close STATF;
187 # ok - count lost and pending mails;
188 my @tmp = grep /^ID/, @messageids;
189 my $pendingm = scalar @tmp;
190 @tmp = grep /^LI/, @messageids;
191 my $lostm = scalar @tmp; 
193 # Evaluate the Warnin/Crit-Levels
194 if (defined $pendwarn && $pendingm > $pendwarn) { $state = 'WARNING'; }
195 if (defined $lostwarn && $lostm > $lostwarn) { $state = 'WARNING'; }
196 if (defined $pendcrit && $pendingm > $pendcrit) { $state = 'CRITICAL'; }
197 if (defined $lostcrit && $lostm > $lostcrit) { $state = 'CRITICAL'; }
199 if ((defined $pendwarn || defined $pendcrit || defined $lostwarn 
200      || defined $lostcrit) && ($state eq 'UNKNOWN')) {$state='OK';}
203 # Append Status info
204 $statinfo = $statinfo . ", $matchcount mail(s) came back,".
205             " $pendingm pending, $lostm lost.";
207 # Exit in a Nagios-compliant way
208 nsexit($statinfo);
210 # ----------------------------------------------------------------------
212 sub usage {
213   print "check_email_loop 1.1 Nagios Plugin - Real check of a E-Mail system\n";
214   print "=" x 75,"\nERROR: Missing or wrong arguments!\n","=" x 75,"\n";
215   print "This script sends a mail with a specific id in the subject via an given\n";
216   print "smtp-server to a given email-adress. When the script is run again, it checks\n";
217   print "for this Email (with its unique id) on a given pop3 account and sends \n";
218   print "another mail.\n";
219   print "\nThe following options are available:\n";
220   print "   -from=text         email adress of send (for mail returnr on errors)\n";
221   print "   -to=text           email adress to which the mails should send to\n";
222   print "   -pophost=text      IP or name of the POP3-host to be checked\n";
223   print "   -popuser=text      Username of the POP3-account\n";
224   print "   -passwd=text       Password for the POP3-user\n";
225   print "   -poptimeout=num    Timeout in seconds for the POP3-server\n";
226   print "   -smtphost=text     IP oder name of the SMTP host\n";
227   print "   -smtptimeout=num   Timeout in seconds for the SMTP-server\n";
228   print "   -statfile=text     File to save ids of messages ($statfile)\n";
229   print "   -interval=num      Time (in minutes) that must pass by before sending\n";
230   print "                      another Ping-mail (gibe a new try);\n"; 
231   print "   -lostwarn=num      WARNING-state if more than num lost emails\n";
232   print "   -lostcrit=num      CRITICAL \n";
233   print "   -pendwarn=num      WARNING-state if more than num pending emails\n";
234   print "   -pendcrit=num      CRITICAL \n";
235   print "   -maxmsg=num        WARNING if more than num emails on POP3 (default 50)\n";
236   print "   -keeporphaned      Set this to NOT delete orphaned E-Mail Ping msg from POP3\n\n";
237   print " Options may abbreviated!\n";
238   print " LOST mails are mails, being sent before the last mail arrived back.\n";
239   print " PENDING mails are those, which are not. (supposed to be on the way)\n";
240   print "\nExample: \n";
241   print " $0 -poph=host -pa=pw -popu=popts -smtph=host -from=root\@me.com\n ";
242   print "      -to=remailer\@testxy.com -lostc=0 -pendc=2\n";
243   print "\nCopyleft 19.10.2000, Benjamin Schmid / 2003 Michael Markstaller, mm\@elabnet.de\n";
244   print "This script comes with ABSOLUTELY NO WARRANTY\n";
245   print "This programm is licensed under the terms of the ";
246   print "GNU General Public License\n\n";
247   exit $ERRORS{"UNKNOWN"};
250 # ---------------------------------------------------------------------
252 sub nsexit {
253   my ($msg,$code) = @_;
254   $code=$state if (!defined $code);
255   print "$code: $msg\n" if (defined $msg);
256   exit $ERRORS{$code};
259 # ---------------------------------------------------------------------
261 sub messagematchsid {
262   my ($mailref,$id) = (@_);
263   my (@tmp);
264   my $match = 0;
265  
266   # ID
267   $id =~ s/^LI/ID/;    # evtl. remove lost mail mark
268   @tmp = grep /E-Mail Ping \[/, @$mailref;
269   chomp @tmp;
270   if (($tmp[0] =~ /$id/)) 
271     { $match = 1; }
273   # Sender:
274 #  @tmp = grep /^From:\s+/, @$mailref;
275 #  if (@tmp && $sender ne "") 
276 #    { $match = $match && ($tmp[0]=~/$sender/); }
278   # Receiver:
279 #  @tmp = grep /^To: /, @$mailref;
280 #  if (@tmp && $receiver ne "") 
281 #    { $match = $match && ($tmp[0]=~/$receiver/); }
283   return $match;
286 # ---------------------------------------------------------------------