python编程实例-使用正则收集IP信息

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-09 02:36:44
 1 #!/usr/bin/env python
 2 
 3 from subprocess import PIPE,Popen
 4 import re
 5 
 6 def getIfconfig():
 7         p = Popen(['ifconfig'],stdout=PIPE)
 8         data = p.stdout.read().split('\n\n')
 9         return [i for i in data if i and not i.startswith('lo')]
10 
11 def parseIfconfig(data):
12         re_devname = re.compile(r'(br|eth|lo|em|virbr|bond)[\d:]+')
13         re_mac = re.compile(r'HWaddr ([0-9A-F:]{17})',re.M)
14         re_ip = re.compile(r'inet addr:([\d\.]{7,15})',re.M)
15         devname = re_devname.search(data)
16         if devname:
17                 devname = devname.group()
18         else:
19                 devname = ''
20         mac = re_mac.search(data)
21         if mac:
22                 mac = mac.group(1)
23         else:
24                 mac = ''
25         ip =re_ip.search(data)
26         if ip:
27                 ip = ip.group(1)
28         else:
29                 ip = ''
30         return {devname : [ip,mac]}
31 
32 if __name__ == '__main__':
33         data = getIfconfig()
34         for i in data:
35                 print parseIfconfig(i)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!