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

Hi Guys! I want get some info from my network devices (more then 100 units). I can't understand how read element of array successively. Now that code working, but use only first IP-address of array - 1.1.1.1.
#!/usr/bin/perl use strict; use warnings; use Net::Appliance::Session; my @ipconadd = qw(1.1.1.1 2.2.2.2 3.3.3.3); my $s = Net::Appliance::Session->new({ personality => 'ios', transport => 'SSH', host => @ipconadd }); eval { $s->connect({ username => 'admin', password => 'coolbro' }); $s->begin_privileged({ password => 'verycoolbro' }); print $s->cmd('show hostname'); print $s->cmd('show inventory | i SN'); $s->end_privileged; }; if ($@) { warn "failed to execute command: $@"; } $s->close;
I would be grateful for any help, Thanks!

Replies are listed 'Best First'.
Re: read IPv4 addresses from array
by GrandFather (Saint) on Aug 18, 2015 at 07:48 UTC

    You probably want something like the following (untested) code:

    #!/usr/bin/perl use strict; use warnings; use Net::Appliance::Session; my @ipconadd = qw(1.1.1.1 2.2.2.2 3.3.3.3); doStuff($_) for @ipconadd; sub doStuff { my ($host) = @_; eval { my $session = Net::Appliance::Session->new( { personality => 'ios', transport => 'SSH', host => $host } ); $session->connect({username => 'admin', password => 'coolbro'} +); $session->begin_privileged({password => 'verycoolbro'}); print $session->cmd('show hostname'); print $session->cmd('show inventory | i SN'); $session->end_privileged; $session->close(); return 1; } or do { my $err = $@; warn "Failed to doStuff for '$host': $@\n"; }; }

    Note the for loop over hosts that calls the sub to do stuff. The loop could be written long hand as:

    for my $host (@ipconadd) { doStuff($host); }
    Premature optimization is the root of all job security
      I knew it! I could do that with "sub" section, but my programming skill too low. Thanks a lot! Your code working very good!
Re: read IPv4 addresses from array
by Corion (Patriarch) on Aug 18, 2015 at 07:48 UTC

    You can iterate over a list (or an array) using the foreach construct (see perlsyn):

    foreach my $ip (@ipconadd) { print "Processing $ip:\n"; # ... print "IP $ip done.\n"; };
      First of all. Thanks for the answer! I tried to use foreach construction, but get many syntax errors.

        If you want help with these "many syntax errors", you will have to show them to us.