1

I have built a script which will do ssh to the remote server and execute certain command. To make execution successful I was waiting until I get END keyword from the command result.

So in positive test case scenario this works fine.

...

foreach my $ip( @list_of_ips ){
    chomp($ip);
    eval {
        $ssh = SSH_Connection( $ip, $user, $passwd );
        print "Connection is Success to $ip\n" if($ssh);
    };

    $command_to_execute = "<forming a command which needs be execute in remote server>";
    print "$command_to_execute\n";

    my $str = 'END';

    eval{
        $ssh->send("$command_to_execute; echo $str");
    };
    $ssh->waitfor($str, undef);
    last if($ssh);
}
...
...

sub SSH_Connection {
    my ( $host, $user, $passwd ) = @_;
    my $ssh = Net::SSH::Expect->new ( host => $host, user => $user, password => $passwd, raw_pty => 1, no_terminal => 0 );

    my $login_output;
    my $handledie = eval {
        $login_output = $ssh->login();
    };

    if ( $@ ) {
        if ($@ =~ m/SSHConnectionError/i ) {
            print  "SSH Connection Error\n";
            next;
        } elsif ( $@ =~ m/SSHProcessError/ix ) {
            print "SSH Process Error\n";
            next;
        } elsif ( $@ =~ m/SSHConnectionAborted/ix ) {
            print "SSH Connection Aborted\n";
            next;
        } else {
            print "SSH Unknown Error: $@\n";
            next;
        }
    }
    if ($login_output !~ /Last login/) {
        die "Login has failed.";
    } else {
        return $ssh;
    }
    print "SSH to ip failed\n";
}

But when connection to remote host is successful and command execution fails, the following error shows up and exits from the script.

SSHProcessError The ssh process was terminated at ...script.pl line 47

We have $ssh->waitfor($str, undef); at line 47.

How can we resolve this issue? TIA.

vkk05
  • 3,137
  • 11
  • 25
  • Does putting the `waitfor()` inside an `eval` block to catch the exception help? – Håkon Hægland May 21 '20 at 14:56
  • @HåkonHægland Yes, sometimes commands failed to execute. thats why I have added the `eval` block. – vkk05 May 21 '20 at 15:00
  • 1
    But the `waitfor()` is not inside the `eval` in your code example – Håkon Hægland May 21 '20 at 15:04
  • What do you mean by *"command execution fails"* ? – Håkon Hægland May 21 '20 at 15:05
  • @HåkonHægland I agree that `waitfor()` should be inside `eval`. Now its not throwing an error. So basically `$ssh->waitfor($str, undef);` will wait for the string `END` from command output. If it doesn't finds it, then wait forever. So wait forever have any time limit? – vkk05 May 21 '20 at 17:11

0 Answers0