Python收集centos7IP地址

2017-01-09 14:10:41来源:http://xtbao.blog.51cto.com/7482722/1889764作者:笑傲博客人点击


Python通过正则收集网卡IP与MAC地址

#!/usr/bin/envpython
#coding=utf-8

importre
fromsubprocessimportPopen,PIPE

defgetIfconfig():
p=Popen(['ifconfig'],stdout=PIPE)
data=p.stdout.read().decode().split('/n/n')
return[iforiindataifiandnoti.startswith('lo')]

defparseIfconfig(data):
re_devname=re.compile(r'^(eth|em|lo|bond)[/d:]+',re.M)
re_mac=re.compile(r'ether([0-9a-f:]{17})',re.M)
re_ip=re.compile(r'inet([/d/.]{7,15})',re.M)
devname=re_devname.search(data)
ifdevname:
devname=devname.group()
mac=re_mac.search(data)
ifmac:
mac=mac.group(1)
else:
mac=''
ip=re_ip.findall(data)
ifip:
ip=ip[0]
else:
ip=''
else:
return
return{devname:[ip,mac]}

if__name__=='__main__':
dic={}
data=getIfconfig()
foriindata:
ifparseIfconfig(i):
dic.update(parseIfconfig(i))
print(dic)

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台