Python通过正则收集网卡IP与MAC地址
#!/usr/bin/env python # coding=utf-8 import re from subprocess import Popen, PIPE def getIfconfig(): p = Popen([‘ifconfig‘], stdout=PIPE) data = p.stdout.read().decode().split(‘\n\n‘) return [i for i in data if i and not i.startswith(‘lo‘)] def parseIfconfig(data): re_devname = re.compile(r‘^(eth|em|lo|bond)[\d:]+‘, re.M) re_mac = re.compile(r‘ether ([0-9a-f:]{17})‘, re.M) re_ip = re.compile(r‘inet ([\d\.]{7,15})‘, re.M) devname = re_devname.search(data) if devname: devname = devname.group() mac = re_mac.search(data) if mac: mac = mac.group(1) else: mac = ‘‘ ip = re_ip.findall(data) if ip: ip = ip[0] else: ip = ‘‘ else: return return {devname: [ip, mac]} if __name__ == ‘__main__‘: dic = {} data = getIfconfig() for i in data: if parseIfconfig(i): dic.update(parseIfconfig(i)) print(dic)
时间: 2024-10-14 16:16:34