SSH connections occasionally die randomly, and the computer I'm connecting to may also occasionally refuse connection. What I want is something that will allow me to continue whenever one of these errors occurs, rather than just dying and require a restart of the entire process.
To give you a small example, here is one function from my package, which is layered on top of Net::SFTP, which is in turn layered on top of Net::SSH::Perl:
sub openConnection {
my $self = $_[0];
local $SIG{'__DIE__'} = sub {};
local $SIG{'__WARN__'} = sub {};
$self->{'sftp'} = Net::SFTP->new($::config{'ahost'},
user => $::config{'auser'},
password => $::config{'apass'},
ssh_args => [
options => [
'ConnectTimeout 30',
'ServerAliveInterval 20',
'ServerAliveCountMax 3'
]
]
);
if (!$self->{'sftp'}) {
$self->{'error'} = "Unable to open SFTP connection";
return;
}
print "SFTP connection opened.\n";
return 1;
}
This connects just fine when I use the correct credentials and the target server is running, but when I test it with a bad password or turn the target server off, I get a die from Net::SSH::Perl and that die does not get caught - even though I have
$SIG{'__DIE__'} set. Wrapping the login inside eval { } causes scoping problems, and putting everything in a separate script and calling it via the command-line adds 30 seconds of overhead per transfer attempt, so those don't look like options either. What am I supposed to do?
I want to catch the die, detect that the connection attempt failed, and return false. Or turn off die somehow.