Question

I have a script which helps me to login to a cisco switch nad run the mac-address table command and save it to an array @ver. The script is as follows:

#!/usr/bin/perl 
use strict;
use warnings;
use Net::Telnet::Cisco;

my $host = '192.168.168.10';

 my $session = Net::Telnet::Cisco->new(Host => $host, -Prompt=>'/(?m:^[\w.&-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/');

$session->login(Name => 'admin',Password => 'password');
my @ver = $session->cmd('show mac-address-table dynamic');
for my $line (@ver)
{
    print "$line";
    if ($line =~ m/^\*\s+\d+\s+(([0-9a-f]{4}[.]){2}[0-9a-f]{4})\s+/ ){
            my $mac_addr = $1;
            print ("$mac_addr \n");
     }
}
$session->close();

It get the following results:

Legend: * - primary entry
    age - seconds since last seen
    n/a - not available

vlan   mac address     type    learn     age              ports
------+----------------+--------+-----+----------+--------------------------
*   14  782b.cb87.b085   dynamic  Yes          5   Gi4/39
*  400  c0ea.e402.e711   dynamic  Yes          5   Gi6/17
*  400  c0ea.e45c.0ecf   dynamic  Yes          0   Gi11/43
*  400  0050.5677.c0ba   dynamic  Yes          0   Gi1/27
*  400  c0ea.e400.9f91   dynamic  Yes          0   Gi6/3

Now, with the above script I am trying to get the mac address and store it in $mac_addr. But I am not getting the desired results. Please can someone guide me. Thank you.

Was it helpful?

Solution

I'm not clear when you say you're not getting the desired results. I did notice that you are first printing your $line and then printing $mac_addr afterwards, besides that your expression seems to match.

Your regular expression matching your desired data.

If you simply just want the matches, you could do..

for my $line (@ver) {
   if (my ($mac_addr) = $line =~ /((?:[0-9a-f]{4}\.){2}[0-9a-f]{4})/) {
     print $mac_addr, "\n";
   }
}

Output

782b.cb87.b085
c0ea.e402.e711
c0ea.e45c.0ecf
0050.5677.c0ba
c0ea.e400.9f91

OTHER TIPS

If you want to print out the mac addresses, you can do the following:

/^\*/ and print +(split)[2], "\n" for @ver;

Note that this splits the line (implicitly on whitespace) if it begins with *; the mac address is the second element in the resulting list (in case you still need to set $mac_addr).

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top