You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则匹配ifconfig输出的设备名、IP及MAC?求Python3实现

匹配ifconfig输出中的设备名、IP和MAC地址

需求背景

需要从ifconfig输出中提取设备名、IPv4地址和MAC地址,已知回环设备(如lo)没有MAC地址,需兼容这种情况。现有三个正则片段:

  • 设备名:r'([^\s]+):\s'
  • MAC地址:r'ether (\w\w:\w\w:\w\w:\w\w:\w\w:\w\w)'
  • IPv4地址:r'inet\s+([^\s]+)'

正则表达式优化方案

直接用.*?拼接会出现跨块匹配的问题,应该按网卡信息块为单位匹配,将MAC地址设为可选捕获组,同时兼容有MAC的物理网卡和无MAC的回环设备。

最终正则模式(结合多行模式与单行模式,确保精准匹配单块网卡信息):

r'^(\S+):.*?inet\s+(\S+).*?(?:ether\s+(\S+))?.*?(?=\n\n|\Z)'
  • ^(\S+)::匹配行首的设备名(非空白字符+冒号)
  • .*?inet\s+(\S+):非贪婪匹配到IPv4地址并捕获
  • .*?(?:ether\s+(\S+))?:可选匹配MAC地址,(?:...)为非捕获组,?表示该部分可不存在
  • .*?(?=\n\n|\Z):匹配到下一个网卡块的分隔符(两个换行)或文本结尾

Python 3 实现代码

import re

ifconfig_output = """eno2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 111.111.111.111  netmask 255.255.255.0  broadcast 111.111.111.111
        ether 1a:2b:3c:4d:5e:6f  txqueuelen 1000  (Ethernet)
        RX packets 149694  bytes 162604639 (155.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 98703  bytes 13286845 (12.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 38  bytes 3424 (3.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 38  bytes 3424 (3.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
"""

# 编译正则,启用多行模式(M)和单行模式(S):M让^匹配行首,S让.匹配换行符
pattern = re.compile(r'^(\S+):.*?inet\s+(\S+).*?(?:ether\s+(\S+))?.*?(?=\n\n|\Z)', re.M | re.S)

# 提取所有匹配结果
results = pattern.findall(ifconfig_output)

# 格式化输出
for dev, ip, mac in results:
    print(f"设备名: {dev}")
    print(f"IPv4地址: {ip}")
    print(f"MAC地址: {mac if mac else '无'}")
    print("---")

运行输出

设备名: eno2
IPv4地址: 111.111.111.111
MAC地址: 1a:2b:3c:4d:5e:6f
---
设备名: lo
IPv4地址: 127.0.0.1
MAC地址: 无
---

内容的提问来源于stack exchange,提问作者bob charliepoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 09:32:01