I am trying to debug a perl script to parse of a snmpwalk
output on a table containing a IPv6 address with Port details.
The snmpwalk
command execution and result on shell is as follows:
[root@newton log]# /usr/bin/snmpwalk -v 2c -c secret localhost SNMP-TARGET-MIB::snmpTargetAddrTAddress
SNMP-TARGET-MIB::snmpTargetAddrTAddress.'2' = Hex-STRING: FD 22 1A 16 0E D3 01 00 00 00 00 00 00 10 00 41
00 A2
The perl script tries to get the value after snmpTargetAddrTAddress.
-> that is 2 and then tries to get value after Hex-STRING
. It uses the following regular expression in code
@buf = `$snmpwalk $address_oid`;
foreach (@buf) {
if (/snmpTargetAddrTAddress\.'(.+?)' = Hex-STRING: ([\w ]+)/)
my $name = $1;
my $rest= $2;
log_msg( LOG_CRIT, "Found IP $rest for $name" );
}
$1 is equal to 2
$2 is equal to FD 22 1A 16 0E D3 01 00 00 00 00 00 00 10 00 41
But I need the value 00 A2
that appears in newline in shell as well.
I tried the online tool - https://regex101.com/ . It provided the regex as ([\w ]+)(\n[\w ]+). But in using in the code, I don't get any output.
The following does not output any
if (/snmpTargetAddrTAddress\.'(.+?)' = Hex-STRING: ([\w ]+)(\n[\w ]+)/
What could I be doing wrong? The expression above in the online tool, yields the results. What other regex can I use if I need to get the characters appearing in newline in the shell output?
Code after @GMB suggestion:
if(/snmpTargetAddrTAddress\.'(.+?)' = Hex-STRING: ([\w\s\n]+)/) {
my $name = $1;
my $rest = $2;
log_msg( LOG_CRIT, "Found IP $rest for $name" );
}
The log seen is: " Found IP FD 22 1A 16 0E D3 01 00 00 00 00 00 00 10 00 41 for 2"
Update: Based on the comments from @zdim & @ikegami, I was wrong in assuming that "00 A2" would be part of the second iteration itself. Since they appear in third line, they are seen in the third iteration of the foreach
Why not simply add the new line character to the list of allowed characters? Actually, as commented by zdim , \s
matches both the space and the new line characters, so you could just do:
/snmpTargetAddrTAddress\.'(.+?)' = Hex-STRING: ([\w\s]+)/
If needed, you can then remove it from the parsed value:
use strict;
use warnings;
my $str = qq/SNMP-TARGET-MIB::snmpTargetAddrTAddress.'2' = Hex-STRING: FD 22 1A 16 0E D3 01 00 00 00 00 00 00 10 00 41\n00 A2/;
if (my ($addr, $hex) = ($str =~ /snmpTargetAddrTAddress\.'(.+?)' = Hex-STRING: ([\w\s]+)/)) {
$hex =~ s/\n/ /;
print "addr: $addr\nhex: $hex\n"
}
Yields:
addr: 2
hex: FD 22 1A 16 0E D3 01 00 00 00 00 00 00 10 00 41 00 A2
Try Hex-STRING:\s+([a-fA-F0-9]{2}(?:\s*[a-fA-F0-9]{2})*)
for that part
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.