我正在尝试从戴尔的RACADM输出中提取每个网卡的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
每个组件详细信息显示在------行之间
我想搜索设备类型 = NIC,然后打印实例 ID 和永久 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 文件内容,您可以尝试使用配置解析器解析它们。
>>> 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
>>>