下面通过两种方法实现收集IP信息
1、通过 ifconfig 命令输出IP信息,并以“\n\n”切片分成不同的网卡块
2、通过 ifconfig 命令输出IP信息,并以第一个字符在顶格的方式切片分成不同的网卡块
3、通过 ifconfig 命令输出IP信息,并用正则表达式来获得
# vim ip1.py
#!/usr/bin/env python from subprocess import Popen, PIPE 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): dic = {} for lines in data: line_list = lines.split('\n') devname = line_list[0].split()[0] macaddr = line_list[0].split()[-1] ipaddr = line_list[1].split()[1].split(':')[1] dic[devname] = [ipaddr, macaddr] return dic if __name__ == '__main__': data = getIfconfig() print parseIfconfig(data) |
验证结果如下:
# vim ip2.py
#!/usr/bin/env python from subprocess import Popen, PIPE def getIP(): p = Popen(['ifconfig'], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() data = [i for i in stdout.split('\n') if i] return data def genIP(data): new_line = '' lines = [] for line in data: if line[0].split(): lines.append(new_line) new_line = line + '\n' else: new_line += line + '\n' lines.append(new_line) return [i for i in lines if i and not i.startswith('lo')] def parseIfconfig(data): dic = {} for lines in data: line_list = lines.split('\n') devname = line_list[0].split()[0] macaddr = line_list[0].split()[-1] ipaddr = line_list[1].split()[1].split(':')[1] dic[devname] = [ipaddr, macaddr] return dic if __name__ == '__main__': data = getIP() data_list = genIP(data) print parseIfconfig(data_list) |
验证结果如下:
# vim ip3.py
#!/usr/bin/env python import re from subprocess import Popen, PIPE 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|bound)[\d:]+',re.M) 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 |
验证结果如下:
可以看到三个方法的输出结果都是一样的字典,但是数据结构不同,第一种方法适合ifconfig命令执行后输出的网卡信息之间存在一个空行,第二种方法是系统比较通用的。第三种是通过正则方式来获得。