Search code examples
regexperltelnet

Processing the output from Perl script


With this code the result in the log file is always the total output.

I also tried passing the regex expression inside a variable but without luck.

The idea is to print into a log file all of the output from the command until it reaches a line that starts with known.

Please share your ideas or what you'd consider the proper approach.

use strict;
use warnings;

use Net::Telnet;

my $telnet = new Net::Telnet( Timeout => 10, Errmode => 'die' );
my $logfile = 'Rogues.log';
my @hosts;
my $debug = 1;

$hosts[0] = 'xxx.xxx.xxx.xxx';

$telnet->open( "$hosts[0]" ) or die $telnet->errmsg;

$telnet->waitfor( '/Please login: $/i' );
$telnet->print( 'USERHERE' ) or die $telnet->errmsg;

$telnet->waitfor( '/Password: $/i' );
$telnet->print( 'PASSWORDHERE' ) or die $telnet->errmsg;

$telnet->waitfor( '/XXXX>/' );
$telnet->cmd( 'enable' ) or die $telnet->errmsg;

my @output = $telnet->cmd( 'show rogue-devices' ) or die $telnet->errmsg;

$telnet->close();

foreach my $index ( @output ) {

    if ( ( $index ne /^Known\/Recognized\sRogue\sDevices:/ )
            || ( $index ne /^User\sBlocked\sRogue\sDevices:/ ) ) {

        if ( $debug ) { }

        open( my $fh, '>>', 'ZD_Rogues.log' ) or die "Could not open file $logfile $!";
        print $fh "\n $index";
        close $fh;
    }
}

print "Export Finished. $logfile";

Update

Hi, the output is made of 3 groups. "Current Active Rogue Devices" followed by "Known/Recognized Rogue Devices" then followed by "User Blocked Rogue Devices:" all with the same content: Rogue Devices: Mac Address= XXX Channel= XXX Radio= XXX Type= XXX Encryption= XXX SSID= XXX Last Detected= XXX


Solution

  • You can exit the loop using last when you reach one of your stop lines. Note that regexes match case-sensitively... if you want to be case-insensitive, add the i flag to the end of your regex: /regex/i.

    for my $index (@output) {
        last if $index =~ /^Known\/Recognized Rogue Devices/
             || $index =~ /^User Blocked Rogue Devices/;
    
        print "$index\n";
    }