[英]Extract IPv4 address from ifconfig output using regex
嘿,我需要一点帮助来尝试使用 python 中的“重新”导入来获取网关 IP。 (我正在尝试在 eth0 中获取“广播”位)任何人都可以帮助我处理正则表达式。 非常感谢。
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 fe80::a00:27ff:feb4:9403 prefixlen 64 scopeid 0x20<link>
ether 08:00:27:b4:94:03 txqueuelen 1000 (Ethernet)
RX packets 81508 bytes 94760761 (90.3 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 80331 bytes 134321242 (128.0 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
不知道为什么要对 ifconfig 的 shell output 使用正则表达式,这很容易受到 *nix、bsd 等分布之间的变化的影响。
这是一个纯 python 解决方案:
>>> import netifaces as ni
>>> ni.ifaddresses('en0')[2][0]['broadcast']
u'192.168.0.255'
好吧,这是两种方式。 任你选。
import re
s = """
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 fe80::a00:27ff:feb4:9403 prefixlen 64 scopeid 0x20<link>
ether 08:00:27:b4:94:03 txqueuelen 1000 (Ethernet)
RX packets 81508 bytes 94760761 (90.3 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 80331 bytes 134321242 (128.0 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
"""
# Bit values - see /usr/include/linux/if.h
IFF_UP = 1<<0
IFF_BROADCAST = 1<<1
IFF_RUNNING = 1<<6
IFF_MULTICAST = 1<<12
# Method 1 - Collect the flags integer value.
rf = re.compile(r'flags=(?P<flags>\d+)')
m = rf.search(s)
if m:
flags = int(m.group('flags'))
print('Your flags {0:d} (decimal) is {0:X}'.format(flags, flags))
# Note the bitwise and operator here:
if flags & IFF_BROADCAST:
print('BROADCAST bit is ON')
# Method 2 - Collect the flag names.
rn = re.compile(r'flags=\d+<(?P<names>.+)>')
m = rn.search(s)
if m:
names = m.group('names').split(',')
print('Your names are ', names)
if 'BROADCAST' in names:
print('BROADCAST bit is ON')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.