I have created a perl that telnet to multiple switches. I would like to check if telnet functions properly by telneting the switch.
This is my code to telnet to the switches:
#!/usr/bin/perl
use warnings;
use Net::Cisco;
open( OUTPUT, ">log.txt" );
open( SWITCHIP, "ip.txt" ) or die "couldn't open ip.txt";
my $count = 0;
while (<SWITCHIP>) {
chomp($_);
my $switch = $_;
my $tl = 0;
my $t = Net::Telnet::Cisco->new(
Host => $switch,
Prompt =>
'/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
Timeout => 5,
Errmode => 'return'
) or $tl = 1;
my @output = ();
if ( $tl != 1 ) {
print "$switch Telnet success\n";
}
else {
my $telnetstat = "Telnet Failed";
print "$switch $telnetstat\n";
}
close(OUTPUT);
$count++;
}
This is my output status after I was testing 7 switches:
10.xxx.3.17 Telnet success
10.xxx.10.12 Telnet success
10.xxx.136.10 Telnet success
10.xxx.136.12 Telnet success
10.xxx.188.188 Telnet Failed
10.xxx.136.13 Telnet success
I would like to convert the telnet result as log file.
How to separate successful and failed telnet results by using perl?
In print statement after print just write the filehandle name which is OUTPUT
in your code:
print OUTPUT "$switch Telnet success\n";
and
print OUTPUT "$switch $telnetstat\n";
A side note: always use a lexical filehandle and three arguments with error handling to open a file. This line open(OUTPUT, ">log.txt");
you can write like this:
open my $fhout, ">", "log.txt" or die $!;