标签:学习 day 正则表达 env proc out main date eth
使用正则表达式收集主机信息
#!/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‘]}
python学习:使用正则收集ip信息
标签:学习 day 正则表达 env proc out main date eth
原文地址:http://www.cnblogs.com/weifeng1463/p/7521492.html