#!/usr/bin/perl ### ### CHECKPORT.PL ### (c) 2003 Software Poetry, Inc. ### http://www.softwarepoetry.com/webob ### ### Verify that a server is alive by opening a port and, for some protocols, ### looking for a success string. Note the USE statements below for ### required modules ... use "perl -MCPAN '-e install Net::POP3'" or similar ### if any are missing. ### ### Usage: perl checkport.pl host timeout protocol [port] ### host = name or ip of server ### timeout = timeout in seconds ### protocol = tcp/ftp/pop3/smtp (tcp == just open a socket) ### port = port number (optional if protocol is not tcp) ### ### License: This software is provided as-is with NO WARRANTY WHATSOEVER. ### Software Poetry makes no claims as to its fitness for any purpose. ### This file and any derivatives or translations of it may be freely ### copied and redistributed so long as the original license and copyright ### notices are included and not altered. ### use strict; use IO::Socket::INET; use Net::FTP; use Net::POP3; use Net::SMTP; # +------------------------------------------------------------------------- # | Entrypoint # +------------------------------------------------------------------------- if (($#ARGV < 2) || (($#ARGV < 3) && @ARGV[0] eq 'tcp')) { print "Usage: checkport.pl host timeout protocol [port]\n"; print " host = name or ip of server\n"; print " timeout = timeout in seconds\n"; print " protocol = tcp/ftp/pop3/smtp (tcp == just open a socket)\n"; print " port = port number (optional if protocol is not tcp\n"; exit(1); } my $szHost = @ARGV[0]; my $csecTimeout = @ARGV[1]; my $szProto = @ARGV[2]; my $nPort; my $fConnectedOK; if ($#ARGV >= 3) { $nPort = @ARGV[3]; } else { $nPort = 0; } $fConnectedOK = 0; if ($szProto eq 'tcp') { my $sock = IO::Socket::INET->new(PeerAddr => $szHost, PeerPort => $nPort, Timeout => $csecTimeout); if ($sock) { $fConnectedOK = 1; $sock->shutdown(2); } } elsif ($szProto eq 'ftp') { my $ftp = Net::FTP->new($szHost, Timeout => $csecTimeout, Port => (($nPort == 0) ? 21 : $nPort)); if ($ftp) { $fConnectedOK = 1; $ftp->quit; } } elsif ($szProto eq 'pop3') { my $pop3 = Net::POP3->new($szHost, Timeout => $csecTimeout, Port => (($nPort == 0) ? 110 : $nPort)); if ($pop3) { $fConnectedOK = 1; $pop3->quit; } } elsif ($szProto eq 'smtp') { my $smtp = Net::SMTP->new($szHost, Timeout => $csecTimeout, Port => (($nPort == 0) ? 25 : $nPort)); if ($smtp) { $fConnectedOK = 1; $smtp->quit; } } else { print "unknown protocol $szProto\n"; exit(2); } if (!$fConnectedOK) { print "connect failed\n"; exit(3); } print "connected ok\n"; exit(0);