Python - 显示 Findall(regex, output) 前后的键值

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

我正在尝试从 Dell 的 RACADM 输出中为每个 NIC 提取 MAC 地址,这样我的输出应该如下所示:

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

我使用以下方法提取输出

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

部分输出

https://pastebin.com/cz6LbcxU

每个组件的详细信息显示在 ------ 行之间

我想搜索 Device Type = NIC,然后打印 Instance ID 和 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)

我使用了上述两个函数来提取匹配项,但是如何打印匹配正则表达式的 [InstanceID: NIC.Slot.2-2-1]PermanentMACAddress

请帮助任何人?

如果我没理解错的话, 您可以搜索模式 [InstanceID: ...] 以获取实例 ID, 和 PermanentMACAddress = ... 获取 MAC 地址。

这是一种方法:

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

如果您有多个这样的记录并希望将 NIC 映射到 MAC,您可以获得每个记录的列表,将它们压缩在一起以创建一个字典:

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

mapping = dict(zip(inst, mac))

您的输出看起来像 INI 文件内容,您可以尝试使用 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
>>>