#!perl use strict; use warnings; use Getopt::Long qw(:config no_ignore_case); use Socket qw(inet_ntoa AF_INET IPPROTO_TCP); use Net::SSH2; # Conditional use of IO::Socket::IP, older than 5.16 doesn't have by default my $HAVE_IO_Socket_IP = 0; eval "use IO::Socket::IP -register"; if(!$@) { $HAVE_IO_Socket_IP = 1 } else { eval "use IO::Socket::INET" } # Backward compatible, older versions of Socket don't have AF_INET6 my $AF_INET6 = eval { Socket::AF_INET6() }; # Get command line options for IPv4 or IPv6 and host my %opt; GetOptions( '4!' => sub { $opt{family} = AF_INET}, '6!' => sub { $opt{family} = $AF_INET6}, 'host' => $opt{host}, ); # If IPv6 and we don't have IO::Socket::IP, fail if (!$HAVE_IO_Socket_IP && defined $opt{family} && ($opt{family} == $AF_INET6)) { print "$0: IO::Socket::IP required for IPv6\n"; exit 1 } # Default to IPv4 for backward compatiblity - THIS MAY CHANGE IN THE FUTURE!!! if (!defined $opt{family}) { $opt{family} = AF_INET } # Open socket my $socket; if ($HAVE_IO_Socket_IP) { $socket = IO::Socket::IP->new( PeerHost => $opt{host}, PeerPort => 22, Family => $opt{family}, ) } else { $socket = IO::Socket::INET->new( PeerHost => $opt{host}, PeerPort => 22, ) } # Open Net::SSH2 connection with the IO::Socket::IP object my $ssh2 = Net::SSH2->new(); if ($ssh2->connect($socket)) { print "[Connected]\n"; # DO STUFF } else { warn "Unable to connect to host $opt{host}: $!\n" }