Perl Parse word from command output


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Perl Parse word from command output
# 1  
Old 01-04-2011
Perl Parse word from command output

Hello,

I used the following script to conect to cisco router:
Code:
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Opsware::NAS::Connect;
my($host, $port, $user, $pass) = ('localhost','$tc_proxy_telnet_port$','$tc_user_username$','$tc_user_password$');
my $device = '#$tc_device_id$';
my @output;
my $con = Opsware::NAS::Connect->new(-user => $user, -pass => $pass, -host => $host, -port => $port);
$con->login();
$con->connect( $device ) or die "Failed to connect.";
$con->cmd("terminal length 0");
 
print "sh run int tu0\n";
@output = $con->cmd("sh run int tu0");
print join("\n", @output);
@output = $con->disconnect();
$con->logout();
undef $con;
exit(0);

I want to parse the bandwidth value of the following "sh run int tu0" command output:

Code:
Building configuration...
Current configuration : 454 bytes
!
interface Tunnel0
 description T.E.Data Tunnel to Giza2 Tu52 1M
 bandwidth 1000
 ip address 10.214.2.6 255.255.255.252
 no ip redirects
 no ip unreachables
 no ip proxy-arp
 ip mtu 1476
 ip nat outside
 ip virtual-reassembly
 zone-member security Outside
 ip summary-address eigrp 1 10.14.2.0 255.255.255.0 5
 no ip mroute-cache
 load-interval 30
 cdp enable
 tunnel source 10.217.2.222
 tunnel destination 10.217.1.254
 tunnel path-mtu-discovery
end

I want to parse the value of "1000" of the output "bandwidth 1000" and put it in variable.

Thanks in advance,
Ahmed
# 2  
Old 01-04-2011
Hey Ahmed.

In:
Quote:
Originally Posted by ahmed_zaher
Code:
print "sh run int tu0\n";
@output = $con->cmd("sh run int tu0");
print join("\n", @output);

You may want to set the output record and field separators:
Code:
$\ = $, = "\n";

So you don't have to keep adding them to your print lines, thusly:
Code:
print 'sh run int tu0';
@output = $con->cmd("sh run int tu0");
print @output;

So to your question, I propose that after the above mentioned code, you add:
Code:
my $output = join $,, @output;
my ($bandwidth) = $output =~ m{^\s*bandwidth (\d+)$}m;

Adding the m suffix changed the meaning of the ^ and $ anchors, as detailed in perlre:
Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end of any line anywhere within the string.
I munged everything into $output so that you could extract other fields in the future. If you need the bandwidth, odds are you will need another field at some point.

I realize there are probably shorter and more perlish ways to extract the value of a field from a multiple line string, and look forward to other suggestions.
# 3  
Old 01-04-2011
Many thanks for your support.

it works fine but after adding
Code:
$\ = $, = "\n";

as per your advice.

but how to specify the 3rd or 4th ,.., etc for each line.

appreaciate your reply.\

Thanks
Ahmed
# 4  
Old 01-04-2011
I am glad that you find my posting useful.

You asked:
Quote:
Originally Posted by ahmed_zaher
<snip>
but how to specify the 3rd or 4th ,.., etc for each line.
<snip>
3rd or 4th what?
# 5  
Old 01-04-2011
Many thanks for your swift response.

I mean 2nd word, 3rd word, 4th word, .. ,etc

for example, how to parse "1476" form "ip mtu 1476"
or "10.14.2.0" from "ip summary-address eigrp 1 10.14.2.0 255.255.255.0 5"

I want a template to use for every command output.

Thanks again,
Ahmed
# 6  
Old 01-04-2011
There are many many ways to do this. But if it were me:
Code:
#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
use Opsware::NAS::Connect;

my ($host, $port, $user, $pass) = ('localhost', '$tc_proxy_telnet_port$', '$tc_user_username$', '$tc_user_password$');
my $device = '#$tc_device_id$';

my $con = Opsware::NAS::Connect->new(-user => $user, -pass => $pass, -host => $host, -port => $port) or die;

$con->login();
$con->connect($device) or die "Failed to connect.";
$con->cmd("terminal length 0");
 
my %X;

foreach ($con->cmd("sh run int tu0")) {
    my ($param, @F) = split;

    if ($param eq 'bandwidth') {
        $X{bandwidth} = $F[0];
        next;
    }

    if ($param eq 'description') {
        $X{description} = join ' ', @F;
        next;
    }
    
    if ($param eq 'ip') {
        # ip address            10.214.2.6 255.255.255.252
        # ip mtu                1476
        # ip nat                outside
        # ip virtual-reassembly
        # ip summary-address    eigrp 1 10.14.2.0 255.255.255.0 5

        if ($F[0] eq 'address')         { $X{address}        = $F[1]; next; }
        if ($F[0] eq 'summary-address') { $X{summaryaddress} = $F[3]; next; }
    
        next;
    }

    if ($param eq 'tunnel') {
        # tunnel source      10.217.2.222
        # tunnel destination 10.217.1.254
        # tunnel path-mtu-discovery

        $X{'tunnel' . $F[0]} = $F[1];
        next;
    }
}

print '   ip address: ', $X{address};
print '      summary: ', $X{summaryaddress};
print '    bandwidth: ', $X{bandwidth};
print 'tunnel-source: ', $X{tunnelsource};
print ' -destination: ', $X{tunneldestination};


$con->disconnect();
$con->logout();

Again, this is not the most perlish code one could write, but I would not be scratching my head wondering what I was trying to do if I looked at this code a year from now. No, wait, I would still scratch my head -- this needs more comments. Smilie

Last edited by m.d.ludwig; 01-04-2011 at 10:05 AM.. Reason: typo
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Need help to parse iostat command output

Hi, I got the code below is one of the threads from this forum. lineCount=$(iostat | wc -l) numDevices=$(expr $lineCount - 7); iostat $interval -x -t | awk -v awkCpuFile=$cpuFile -v awkDeviceFile=$deviceFile -v awkNumDevices=$numDevices ' BEGIN { print... (2 Replies)
Discussion started by: gopivallabha
2 Replies

2. UNIX for Advanced & Expert Users

Perl command to replace word in file...

Hi, I want to search for a specific word in file and replace whole line with new text. e.g. 1) I have file with below lines APP=ABCD 12/12/2012 DB=DDB 01/01/2013 I need perl command which will check for APP=$VAL and replace whole line with APP=$NEWVAL $NEWDT Simlarly need a... (2 Replies)
Discussion started by: mgpatil31
2 Replies

3. Shell Programming and Scripting

Modify a perl line to parse out and output to another format

Hey there... I am looking for a way to take the below contents ( small excerpt) of this file called PTR.csv ptrrecord,0000002e0cc0.homeoffice.anfcorp.com,,10.11.191.62,,,False,62.191.11.10.in-addr.arpa,,302400,default... (6 Replies)
Discussion started by: richsark
6 Replies

4. Shell Programming and Scripting

Output of a command in perl

Hi All If i run the following command nvidia-settings -V -q screens I get this output X Screen on sutton:0 sutton:0.0 (Quadro FX 4600) Is connected to the following display devices: DELL 2007FP (DFP-0: 0x00010000) Eizo CG243W (DFP-1:... (1 Reply)
Discussion started by: ab52
1 Replies

5. UNIX for Dummies Questions & Answers

How to parse 2 particular lines from Command output

Hi All, I need help on the following req. I am getting output of a command as follows: 16377612 total memory 3802460 used memory 2827076 active memory 681948 inactive memory 12575152 free memory 477452 buffer memory I want to compute used... (1 Reply)
Discussion started by: mailsara
1 Replies

6. Shell Programming and Scripting

Perl script to parse output and print it comma separated

I need to arrange output of SQL query into a comma separated format and I'm struggling with processing the output... The output is something like this: <Attribute1 name><x amount of white spaces><Atribute value> <Attribute2 name><x amount of white spaces><Atribute value> <Attribute3... (2 Replies)
Discussion started by: Juha
2 Replies

7. Shell Programming and Scripting

Command to parse a word character by character

Hi All, Can anyone help me please, I have a word like below. 6,76 I want to read this word and check if it has "," (comma) and if yes then i want to replace it with "." (dot). That means i want to be changed to 6.76 If the word doesnot contain "," then its should not be changed. Eg. ... (6 Replies)
Discussion started by: girish.raos
6 Replies

8. Shell Programming and Scripting

Perl Parse Word Cksum help

Hi all, I'm attempting to parse through a .bin file word by word and perform a cksum on each word using perl. I'm new to perl so I dont exactly know how to get started. Any help would be greatly appreciated. Thanks! (1 Reply)
Discussion started by: TeamUSA
1 Replies

9. Shell Programming and Scripting

How to parse the given word

Hi , i need to parse the dir /opt/net/Pro/inv/do/disc_001812 to get only dsic001812 . how to do the same using shell script. (2 Replies)
Discussion started by: MuthuAlagappan
2 Replies

10. Shell Programming and Scripting

Perl script assistance; paste word into external command

I'm attempting to create a Perl script that will: Take the contents of the usernames.tmp file (usernames.tmp is created from an awk one-liner ran against /etc/passwd) Take one line at a time and pass it to the su command as a users name. This should go on until there is no more name to... (10 Replies)
Discussion started by: bru
10 Replies
Login or Register to Ask a Question