简体   繁体   中英

Python - Display key values before and after Findall(regex, output)

I am trying to extract MAC addresses for each NIC from Dell's RACADM output such that my output should be like below:

NIC.Slot.2-2-1  -->  24:84:09:3E:2E:1B

I have used the following to extract the output

output =  subprocess.check_output("sshpass -p {} ssh {}@{} racadm {}".format(args.password,args.username,args.hostname,args.command),shell=True).decode()

Part of output

https://pastebin.com/cz6LbcxU

Each component details are displayed between ------ lines

I want to search Device Type = NIC and then print Instance ID and Permanent MAC.

regex = r'Device Type = NIC'
match = re.findall(regex, output, flags=re.MULTILINE|re.DOTALL)
match = re.finditer(regex, output, flags=re.S)

I used both the above functions to extract the match but how do I print [InstanceID: NIC.Slot.2-2-1] and PermanentMACAddress of the Matched regex.

Please help anyone?

If I understood correctly, you can search for the pattern [InstanceID: ...] to get the instance id, and PermanentMACAddress = ... to get the MAC address.

Here's one way to do it:

import re

match_inst = re.search(r'\[InstanceID: (?P<inst>[^]]*)', output)
match_mac = re.search(r'PermanentMACAddress = (?P<mac>.*)', output)

inst = match_inst.groupdict()['inst']
mac = match_mac.groupdict()['mac']

print('{}  -->  {}'.format(inst, mac))
# prints: NIC.Slot.2-2-1  -->  24:84:09:3E:2E:1B

If you have multiple records like this and want to map NIC to MAC, you can get a list of each, zip them together to create a dictionary:

inst = re.findall(r'\[InstanceID: (?P<inst>[^]]*)', output)
mac = re.findall(r'PermanentMACAddress = (?P<mac>.*)', output)

mapping = dict(zip(inst, mac))

Your output looks like INI file content, you could try to parse them using configparser .

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read_string(output)
>>> for section in config.sections():
...     print(section)
...     print(config[section]['Device Type'])
... 
InstanceID: NIC.Slot.2-2-1
NIC
>>> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM