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.


In reply to Catching die in Net::SFTP / Net::SSH::Perl: by TedPride

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.