Search code examples
perlloggingswitch-statementtelnetcisco

Perl - Output the log files


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?


Solution

  • Please Try the following

    #!/usr/bin/perl
    use warnings;
    use Net::Cisco;
    ################################### S
    open( OUTPUTS, ">log_Success.txt" );
    open( OUTPUTF, ">log_Fail.txt" );
    ################################### E
    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 = ();
    ################################### S
        if ( $tl != 1 ) {
            print "$switch Telnet success\n"; # for printing it in screen
            print OUTPUTS "$switch Telnet success\n"; # it will print it in the log_Success.txt
        }
        else {
            my $telnetstat = "Telnet Failed";
            print "$switch $telnetstat\n"; # for printing it in screen
            print OUTPUTF "$switch $telnetstat\n"; # it will print it in the log_Fail.txt
        }
    ################################### E
        $count++;
    }
    ################################### S
    close(SWITCHIP);
    close(OUTPUTS);
    close(OUTPUTF);
    ################################### E