从ifconfig(ubuntu)中提取网络信息的算法

sba*_*ell 3 python regex

我试图从ifconfig(ubuntu)解析信息.通常,我会将这样的数据块分成单词,然后搜索子字符串以获得我想要的内容.例如,给定line = "inet addr:192.168.98.157 Bcast:192.168.98.255 Mask:255.255.255.0",并寻找广播地址,我会这样做:

for word in line.split():
    if word.startswith('Bcast'):
        print word.split(':')[-1]

>>>192.168.98.255
Run Code Online (Sandbox Code Playgroud)

但是,我觉得有时间开始学习如何使用正则表达式来完成这样的任务.到目前为止,这是我的代码.我已经破解了几种模式(inet addr,Bcast,Mask).代码后的问题......

# git clone git://gist.github.com/1586034.git gist-1586034
import re
import json

ifconfig = """
eth0      Link encap:Ethernet  HWaddr 08:00:27:3a:ab:47  
          inet addr:192.168.98.157  Bcast:192.168.98.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe3a:ab47/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:189059 errors:0 dropped:0 overruns:0 frame:0
          TX packets:104380 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:74213981 (74.2 MB)  TX bytes:15350131 (15.3 MB)\n\n
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:389611 errors:0 dropped:0 overruns:0 frame:0
          TX packets:389611 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:81962238 (81.9 MB)  TX bytes:81962238 (81.9 MB)
"""

for paragraph in ifconfig.split('\n\n'):

    info = {
        'eth_port': '',
        'ip_address': '',
        'broadcast_address': '',
        'mac_address': '',
        'net_mask': '',
        'up': False,
        'running': False,
        'broadcast': False,
        'multicast': False,
    }

    if 'BROADCAST' in paragraph:
        info['broadcast'] = True

    if 'MULTICAST' in paragraph:
        info['multicast'] = True

    if 'UP' in paragraph:
        info['up'] = True

    if 'RUNNING' in paragraph:
        info['running'] = True

    ip = re.search( r'inet addr:[^\s]+', paragraph )
    if ip:
        info['ip_address'] = ip.group().split(':')[-1]  

    bcast = re.search( r'Bcast:[^\s]+', paragraph )
    if bcast:
        info['broadcast_address'] = bcast.group().split(':')[-1]

    mask = re.search( r'Mask:[^\s]+', paragraph )
    if mask:
        info['net_mask'] = mask.group().split(':')[-1]

    print paragraph
    print json.dumps(info, indent=4)
Run Code Online (Sandbox Code Playgroud)

这是我的问题:

  1. 我对已经实施的模式采取了最佳方法吗?我可以抓住地址而不拆分':'然后选择最后一个数组.

  2. 我被困在HWaddr上了.什么是匹配这个mac地址的模式?

编辑:

好的,所以这就是我最终解决这个问题的方法.我开始试图在没有正则表达式的情况下试图解决这个问题...只是操纵蜇和列表.但事实证明这是一场噩梦.例如,HWaddr与其地址分开的是a space.现在把inet addr它与地址分开:.它是一个完全的婊子,用这样的不同分离器刮掉.不仅是代码的婊子,也是阅读的婊子.

所以,我用正则表达式做到了这一点.我认为这为何时使用正则表达式提供了强有力的理由.

# git clone git://gist.github.com/1586034.git gist-1586034

# USAGE: pipe ifconfig into script. ie "ifconfig | python pyifconfig.py"
# output is a list of json datastructures

import sys
import re
import json

ifconfig = sys.stdin.read()

print 'STARTINPUT'
print ifconfig
print 'ENDINPUT'

def extract(input):
    mo = re.search(r'^(?P<interface>eth\d+|eth\d+:\d+)\s+' +
                     r'Link encap:(?P<link_encap>\S+)\s+' +
                     r'(HWaddr\s+(?P<hardware_address>\S+))?' +
                     r'(\s+inet addr:(?P<ip_address>\S+))?' +
                     r'(\s+Bcast:(?P<broadcast_address>\S+)\s+)?' +
                     r'(Mask:(?P<net_mask>\S+)\s+)?',
                     input, re.MULTILINE )
    if mo:
        info = mo.groupdict('')
        info['running'] = False
        info['up'] = False
        info['multicast'] = False
        info['broadcast'] = False
        if 'RUNNING' in input:
            info['running'] = True
        if 'UP' in input:
            info['up'] = True
        if 'BROADCAST' in input:
            info['broadcast'] = True
        if 'MULTICAST' in input:
            info['multicast'] = True
        return info
    return {}


interfaces = [ extract(interface) for interface in ifconfig.split('\n\n') if interface.strip() ]
print json.dumps(interfaces, indent=4)
Run Code Online (Sandbox Code Playgroud)

syn*_*tel 13

而不是重新发明轮子:

或者,如果您想要一个可在多个平台上运行的便携式版本..


And*_*ark 5

我是否对已经实现的模式采取了最佳方法?我可以获取地址而不用“:”分割,然后选择数组的最后一个吗?

您的模式对于他们正在做的事情来说很好,尽管[^\s]相当于\S.

您可以通过将地址放入捕获组来获取地址,而无需拆分“:”,如下所示:

    ip = re.search(r'inet addr:(\S+)', paragraph)
    if ip:
        info['ip_address'] = ip.group(1)
Run Code Online (Sandbox Code Playgroud)

如果您有更多正则表达式的分组部分,您可以按照它们在正则表达式中出现的顺序引用它们,从 1 开始。

我被困在 HWaddr 上。匹配此 MAC 地址的模式是什么?

现在您已经了解了分组,您可以像其他地址一样获取 HWaddr:

    mac = re.search(r'HWaddr\s+(\S+)', paragraph)
    if mac:
        info['mac_address'] = mac.group(1)
Run Code Online (Sandbox Code Playgroud)

请注意,使用更高级的正则表达式,您实际上可以同时执行其中几个步骤。例如,下面是一个示例正则表达式,它可以一步提取接口名称、IP 地址和网络掩码:

>>> re.findall(r'^(\S+).*?inet addr:(\S+).*?Mask:(\S+)', ifconfig, re.S | re.M)
[('eth0', '192.168.98.157', '255.255.255.0'), ('lo', '127.0.0.1', '255.0.0.0')]
Run Code Online (Sandbox Code Playgroud)