#!/usr/bin/perl # vi: set ts=4 sw=4 sts=2 et: use strict; use warnings; use IO::Socket; use File::Basename qw( basename ); # Author: linuxer # Date: 22. Juli 2008 # Description: # checks if remote host listens to specified port(s) #> global variables (the less you use, the better the script) #> -------------------------------------------------------------------------- our $VERSION = '0.34'; #> sub routines #> -------------------------------------------------------------------------- { my $failed = 0; sub checkport { my $host = shift; my $port = shift; my $socket = IO::Socket::INET->new( PeerAddr => $host, PeerPort => $port, Protocol => q{tcp}, Timeout => 2, ); if ( $socket ) { close $socket; return qq{+ $host tcp/$port reached\n}; } else { $failed++; return qq{- $host tcp/$port NOT reached: $!\n}; } } # sub grand_final { print qq{$failed not reached\n} if ( $failed ); exit $failed; } # } sub print_help { my $program = basename $0; print <<"HELP"; SYNOPSIS $program remote_host tcp_port [tcp_port ...] DESCRIPTION This script simply tries to open a connection to the remote host and the specified port(s). It is meant as a simple check, whether a remote host listens to a specific port (and is reachable). In case the specified port can't be reached, the script generates an error message with a reason. This reason is taken from the system itself. Depending on the system, this reason may be usable (linux; connection refused / timed out) or not (windows; connect failed). EXAMPLE $program localhost 22 checks if localhost is reachable on tcp port 22. HELP } # #> main script #> -------------------------------------------------------------------------- my $remote = shift @ARGV; if ( !$remote or $remote =~ m/\A-/ or ! @ARGV ) { print_help(); exit 0; } # for my $port ( @ARGV ) { print checkport( $remote, $port ) if $port =~ m/\A \d+ \z/x; } grand_final(); __END__