python学习:使用正则收集ip信息

 
 
使用正则表达式收集主机信息 
 
 
 
#!/usr/bin/env python
 
from subprocess import Popen, PIPE
import re
def getIfconfig():
    p = Popen(['ifconfig'], stdout=PIPE)
    data = p.stdout.read().split('\n\n')
    return [i for i in data if i and not i.startswith('lo')]
 
def parseIfconfig(data):
    re_devname = re.compile(r'br|eth|em|virbr|lo|bond[\d:]+',re.M)           使用了正则表达式来收集ip信息 
    re_mac = re.compile(r'HWaddr ([0-9A-F:]{17})', re.M)
    re_ip = re.compile(r'inet addr:([\d\.]{7,15})', re.M)
    devname = re_devname.search(data)
    if devname:
        devname = devname.group()
    else:
        devname = ''
    mac = re_mac.search(data)
    if mac:
        mac = mac.group(1)
    else:
        mac = ''
    ip = re_ip.search(data)
    if ip:
        ip = ip.group(1)
    else:
        ip = ''
    return {devname: [ip,mac]}
 
if __name__ == '__main__':
    dic = {}
    data = getIfconfig()
    for i in data:
        dic.update(parseIfconfig(i))
        print dic
 
 
[root@web10 day03]# python 13_ip.py
{'eth': ['192.168.1.200', '00:0C:29:B7:57:8F']}
 
posted @ 2017-09-14 16:48  Oops!#  阅读(234)  评论(0编辑  收藏  举报