Moniker | 4 | WebReference

Moniker | 4

moniker.pl Source
1  #!/usr/bin/perl -w
2  # INCLUDES
3  use strict;
4  use Net::Telnet;
5  use Mail::Sendmail;
6  use Getopt::Std;
7  
8  # CONSTANTS
9  my $timeout = 5;
10  my $monikeraddr = 'support@wwind.com';
11  my $smtpserver = 'core.iconnet.net';
12  
13  my $services = {
14      ftp    => { port => 21,   print => "", waitfor => '/220/' },
15      ssh    => { port => 22,   print => "", waitfor => '/SSH/' },
16      telnet => { port => 23,   print => "", waitfor => '/(login|username)/' },
17      www    => { port => 80,   print => "HEAD / HTTP/1.0\n\n", waitfor => '/200/' },
18      pop    => { port => 110,  print => "", waitfor => '/\+OK/' },
19      nntp   => { port => 119,  print => "", waitfor => '/200/' },
20      imap   => { port => 143,  print => "", waitfor => '/OK/' },
21      smtp   => { port => 25,   print => "", waitfor => '/SMTP/' }
22  };
23  
24  # MAIN
25  my %opts = ();
26  getopt('hse', \%opts);
27  die "Usage: moniker -h host -s service [-e email]"
28      unless exists($opts{h}) && exists($opts{s});
29  die "Service $opts{s} does not compute.\n" 
30      unless defined $services->{$opts{s}};
31  
32  my $service = $opts{s};
33  my $host    = $opts{h};
34  my $email   = $opts{e} if exists $opts{e};
35  my $port    = $services->{$service}->{port};
36  my $sock    = new Net::Telnet (Telnetmode => 0);
37  my $waitfor = $services->{$service}->{waitfor};
38  
39  # Create a connection to the remote host
40  eval {
41      $sock->open(Host    => $host,
42  		Port    => $port,
43  		Timeout => $timeout
44  		);
45  };
46  
47  # Catch any errors
48  &alert("Cannot establish a connection to specified host") if $@;
49  
50  # send data to remote host
51  $sock->print($services->{$service}->{print}) if $services->{$service}->{print};
52  
53  # wait for regex match
54  &alert("Timed out waiting for $waitfor") unless $sock->waitfor($waitfor);
55      
56  print "Service is operational.\n" unless exists($opts{e});
57  
58  # SUBROUTINES
59  sub alert {
60      my $error = shift;
61      my $message = <<MESSAGE;
62  Moniker Alert
63  -------------
64  Host: $host
65  Port: $port
66  -------------
67  $error
68  MESSAGE
69      
70      print "$message";
71      if (exists($opts{e})) {
72  	sendmail(To      => $email,
73  		 Subject => 'Moniker Alert',
74  		 From    => $monikeraddr,
75  		 Message => $message,
76  		 Server  => $smtpserver,
77  		 delay   => 1,
78  		 retries => 5) 
79  	    || die "Cannot send mail: $Mail::Sendmail::error\n";
80      } 
81      exit;
82  }