in reply to Login to multiple devices using telnet and issue different commands

I would shove the information from the two files into a hash, then iterate over the details in a for loop. I've commented inline. Note the telnet portions are untested:

use warnings; use strict; use Net::Telnet; my $ip_list = 'ip.list'; my $cmd_list = 'commands.list'; # use the three-arg form of open, # and *always* check for problems open my $ip_fh, '<', $ip_list or die "Can't open IP list $ip_list: $!"; my %hosts; while (my $line = <$ip_fh>){ chomp $line; # split the line into host and ip, # then put this information into the %hosts hash my ($host, $ip) = split /,\s*/, $line; $hosts{$host}{ip} = $ip } close $ip_fh; open my $cmd_fh, '<', $cmd_list or die "Can't open CMD list $cmd_list: $!"; while (my $line = <$cmd_fh>){ # append each command to an array reference # under each host in the hash chomp $line; my ($host, $cmd) = split /,\s*/, $line; push @{$hosts{$host}{commands}}, $cmd; } close $cmd_fh; my $log = './log.txt'; open my $log_fh, '>>', $log or die $!; for my $host (keys %hosts){ # I think the instantiation of the object could # be done outside of the for() loop as long as each # session is closed, but I'm unsure my $telnet = new Net::Telnet ( Timeout=>10, Errmode=>'die', # you were missing a comma here Prompt => '/# $/i', ); # extract the ip for the current host my $ip = $hosts{$host}{ip}; $telnet->open($ip); $telnet->login('USERNAME', 'PASSWORD'); # loop over the command array, # and do something for each one for my $cmd (@{$hosts{$host}{commands}}){ if($telnet->cmd($cmd)){ print $log_fh "$ip $cmd successful"; }else{ print $log_fh "$ip Unable to Connect"; } } } close $log_fh;

-stevieb

Replies are listed 'Best First'.
Re^2: Login to multiple devices using telnet and issue different commands
by acondor (Initiate) on Aug 25, 2015 at 17:37 UTC
    Thank you for your reply. I got it to work. When each command processes, how do I print results from the command? I tried putting in "for my" section, but print shows only login message (response from device) but no data from the command.
    for my $cmd (@{$hosts{$host}{commands}}){ if(my @check = $telnet->cmd($cmd)){ my $response = join(" ", @check); print "response below \n"; print $response; print $log_fh "$ip $cmd successful\n"; }else{ print $log_fh "$ip Unable to Connect"; } }

      Try adding logging to the session and look at the results.

      $telnet = new Net::Telnet ( Timeout=>10, Errmode=>'die', Prompt => '/# $/i', Input_log => 'input.log', Dump_log => 'dump.log', );
      poj