Dru has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I have a subroutine using Net::SSH that connects to a server with multiple interfaces. I want it to attempt to connect to each interface and keep trying until it is successfull in which I then want it to run the mail() sub and exit out of that sub (on the server running this script, not the one I'm connecting to). What is the best way to do this?
#!/usr/bin/perl -w use strict; use Net::SSH qw(ssh); my @host = qw[ 192.168.15.2 192.168.14.2 192.168.16.2 192.168.17.2 ]; foreach (@host) { run($_); } sub run { my $host = $_[0]; my $user = 'root'; my $host = 'test-1'; my $cmd = '/usr/local/scripts/down.pl'; ssh("$user\@$host", $cmd); if ($something = somevalue){ mail(); } }
Thanks,
Dru

Replies are listed 'Best First'.
Re: Continue Processing Subrouting Until Successfull
by ides (Deacon) on Jan 08, 2003 at 15:48 UTC

    I think this is what you're wanting:

    foreach (@host) { my $result = 255; while( $result == 255 ) { $result = run($_); } mail(); } sub run { my $host = $_[0]; my $user = 'root'; my $host = 'test-1'; my $cmd = '/usr/local/scripts/down.pl'; return( ssh("$user\@$host", $cmd) ); }

    According to OpenSSH's documentation it returns 255 if there is an error. This should loop until you get success.

    -----------------------------------
    Frank Wiles <frank@wiles.org>
    http://frank.wiles.org
      Frank,

      Thank you for your response. Wouldn't this execute the run sub if $result equals 255? Should I use a until loop instead like:
      until ($result == 255) { $result = run($_); }
      Also, can you plase explain what this does a little more $result = run($_);

      Thanks,
      Dru

        No, the result is 255 until a success. So you want to continue looping until $result is not 255.

        As for the $result = run($_); If you notice I added a return() into the run subroutine. This will return the exit code of the ssh() call, which will be 255 ( according to OpenSSH's documentation ) if there is an error or the exit code of the command being run if there isn't an error.

        If your down.pl script returns a different exit code you'll want to adust your test to not be 255.

        -----------------------------------
        Frank Wiles <frank@wiles.org>
        http://frank.wiles.org
        Why use $result at all
        while (run($_)==255) { shift @hosts; }