Python 使用正则表达式匹配IP信息

使用正则表达式匹配IP地址 、MAC地址 、网卡名称:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import re
from subprocess import Popen, PIPE

def getAddress(data):
    reg_ip = re.compile(r'inet addr:([d.]{7,15})', re.M)
    reg_mac = re.compile(r'HWaddr ([0-9a-zA-Z:]{17})', re.M)
    reg_netcard = re.compile(r'(eth|br|lo|ens|virbr|em)[d]+', re.M)

    ip = reg_ip.findall(data)
    mac = reg_mac.findall(data)
    netcard = reg_netcard.search(data)

    return ip, mac, netcard.group()


if __name__ == '__main__':
    p = Popen('ifconfig', stdout=PIPE)
    data = p.stdout.read()
    ip, mac, netcard = getAddress(data)
    print("IP地址:%s" % ip)
    print("MAC地址:%s" % mac)
    print("网卡名称:%s" % netcard)

   

原文地址:https://www.cnblogs.com/pzk7788/p/10322834.html