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

Hi Monks,

My script terminates if it can not telnet to the host in the array and does not loop through rest of the hosts in the array. How do I force it to continue to other hosts if it fails to telnet one host. here is the script:

use Net::Telnet; @hosts = ("ncc1","ncc2","ncc3") for ($x=0; $x <= $#hosts; $x++) { $telnet = new Net::Telnet ( Timeout=>10, Errmode=>'die'); $telnet->open("$hosts[$x]"); $telnet->login('test', 'testuser'); my @arr = $telnet->cmd('ifconfig -a'); $telnet->close("$host"); print "\n Probe - $host \n"; print "\n @arr \n" ; }

Edit by castaway - fix code tags

Replies are listed 'Best First'.
Re: Net::Telnet
by davidj (Priest) on Jun 22, 2004 at 18:46 UTC
    You need to change the value of Errmode when you initialize the Net::Telnet object.

    Errmode=>'die' tells the program to abort if there is an error (and failing to connect to a host is an error). I would suggest you do the following:
    $telnet = new Net::Telnet ( Timeout=>10, Errmode=>'return');
    which will return undef if there is a connect failure. You can then test the return value of $telnet->open("$hosts$x"); for undef and proceed as you wish. One possibility:
    use Net::Telnet; @hosts = ("ncc1","ncc2","ncc3"); for ($x=0; $x <= $#hosts; $x++) { $telnet = new Net::Telnet ( Timeout=>10, Errmode=>'return'); $result = $telnet->open("$hosts$x"); if($result) { $telnet->login('test', 'testuser'); my @arr = $telnet->cmd('ifconfig -a'); $telnet->close("$host"); print "\n Probe - $host \n"; print "\n @arr \n" ; } else { print $telnet->errmsg . "\n"; } }
    I would suggest you read the Net::Telnet manpage

    Hope this helps,
    davidj
Re: Net::Telnet
by gri6507 (Deacon) on Jun 22, 2004 at 20:27 UTC
    You could also do this (it should be quicker) Note: untested code

    use strict; use Net::Telnet; foreach(@hosts){ if (!fork()) { my $telnet = new Net::Telnet ( Timeout=>10, Errmode=>'die'); $telnet->open($_); telnet->login('test', 'testuser'); my @arr = $telnet->cmd('ifconfig -a'); $telnet->close(); } }