I have created a perl that telnet to multiple switches. My code is generates only one log file output for multiple Cisco switches.
What should I do to create separate log file for each device status(include telnet failure)? And how could I convert IP to hostname from the log filenames?
Desired output log files one by one, hostname1.log, hostname2.log, hostname3.log......so on and so forth.
Here is my code:
#!/usr/bin/perl
use strict;
use warnings;
use Net::Cisco;
my $username="danny";
my $pass="1234";
open (OUTPUT, ">intstatus.log" );
open (IP, "ip.txt") or die $!;
for my $line (<IP>) {
chomp $line;
$line =~ s/\t+//;
print $line, "\n";
SWTELNET($line); # pass $line as the argument to SWTELNET
}
sub SWTELNET {
my $host = shift; # $host is set to the first argument passed in from the above loop
my $t = Net::Telnet::Cisco -> new (
Host => $host,
Prompt => '/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
Timeout => 6,
Errmode => 'return',
) or die "connect failed: $!";
if ($t->login($username,$pass)) {
$t->autopage;
$t->always_waitfor_prompt;
my @supenv=$t->cmd("show ip int br");
my @output = ();
print OUTPUT "$host\n@supenv\n";
}
}
close(IP);
close(OUTPUT);
I don't have any telnet devices to test with, but this should at least get you most of the way. It uses
gethostbyaddr()from Socket to try to resolve the IP back to a hostname (and falls back to using the IP as hostname if the name can't be found). It also uses the proper three-argument form of open with lexical file handles (as opposed to bareword handles), and it opens a new log file for writing in the formathostname.logfor each host found in the input file.