vkk05
vkk05

Reputation: 3222

Retry SSH to Host if Connection to the Host Fails in Perl

I have a script, which does SSH to the server and execute some command (In this script, for demonstration I am running Perl print statement with Hello message).

Here is my script:

#!/usr/bin/perl 

use strict; use warnings;

use Net::OpenSSH;

$Net::OpenSSH::debug = ~0;

BEGIN {
  open my $out, '>', '/tmp/debug.txt' or warn $!;
  $Net::OpenSSH::debug_fh = $out;
  $Net::OpenSSH::debug = -1;
}

my @hosts = ("ipaddress1","ipaddress2");

my $ssh;
my $command = "perl -e 'print \"Hello..\"'";

foreach my $n (@hosts) {
    
  #Here if connection to the host($n) fails, is it possible to retry again
  $ssh = Connect($n, "user", "passwd"); 
  $ssh->capture($command);

  print "Done execution in Host: $n\n";
 
}

undef $ssh;
print "**End**\n";

sub Connect {
    my ( $host, $user, $passwd ) = @_;
    my $ssh = Net::OpenSSH->new($host, user=>$user, password=>$passwd);
    $ssh->error and die "Couldn't establish SSH connection: " . $ssh->error;
    return $ssh;
}

Whenever I execute this script, sometimes it successfully prints below message:

Done execution in Host: ipaddress1
Done execution in Host: ipaddress2
**End**

But sometimes cannot do ssh to host (either ipaddress1 or ipaddress2) and gives following message:

Couldn't establish SSH connection: unable to establish master SSH connection: master process exited unexpectedly at script.pl ....

Its being get died in Connect subroutine (cause I couldn't trace, opened question here).

So, is there any way if I cannot connect(ssh) to the host, retry can be done after certain period of time (for n number times) instead of printing error message and make the script die?

Upvotes: 0

Views: 553

Answers (1)

hoffmeister
hoffmeister

Reputation: 612

OpenSSH provides a nice interface for errors. I'd start by looking at the examples on the cpan page. Try the following

 foreach my $n (@hosts) {
    
  #Here if connection to the host($n) fails, is it possible to retry again
  $ssh = Connect($n, "user", "passwd", 3); 
  $ssh->capture($command);

  print "Done execution in Host: $n\n";
 
}

undef $ssh;
print "**End**\n";

sub Connect {
    my ( $host, $user, $passwd , $retry_limit ) = @_;
    my $timeout = 10;
    my $con;
    while ( $retry_limit-- > 0 )
    {
        $con = Net::OpenSSH->new($host, 
            user=>$user, 
            password=>$passwd,
            timeout=> $timeout,
            );
        last unless $con->error();
    }
    die "unable to connect ".$con->error() if retry_limit <0;
    return $con;
}

Upvotes: 2

Related Questions