使用 python 获取 Linux 的 IP 信息(通过 ifconfig 命令)
我们可以使用 python 代码通过调用 ifconfig 命令来获取 Linux 主机的 IP 相关信息,包括:网卡名称、MAC地址、IP地址等。
第一种实现方式:
1 #!/usr/bin/python 2 #encoding: utf-8 3 4 from subprocess import Popen, PIPE 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 dic = {} 13 for devs in data: 14 lines = devs.split('\n') 15 devname = lines[0].split()[0] 16 macaddr = lines[0].split()[-1] 17 ipaddr = lines[1].split()[1].split(':')[1] 18 dic[devname] = [ipaddr, macaddr] 19 return dic 20 21 22 if __name__ == '__main__': 23 data = getIfconfig() 24 print parseIfconfig(data)
第二种实现方式:
1 #!/usr/bin/python 2 #encoding: utf-8 3 4 from subprocess import Popen, PIPE 5 6 def getIP(): 7 p = Popen(['ifconfig'], stdout = PIPE, stderr = PIPE) 8 stdout, stderr = p.communicate() 9 data = [i for i in stdout.split('\n') if i] 10 return data 11 12 def genIP(data): 13 new_line = '' 14 lines = [] 15 for line in data: 16 if line[0].strip(): 17 lines.append(new_line) 18 new_line = line + '\n' 19 else: 20 new_line += line + '\n' 21 lines.append(new_line) 22 return [i for i in lines if i and not i.startswith('lo')] 23 24 def parseIP(data): 25 dic = {} 26 for devs in data: 27 lines = devs.split('\n') 28 devname = lines[0].split()[0] 29 macaddr = lines[0].split()[-1] 30 ipaddr = lines[1].split()[1].split(':')[1] 31 dic[devname] = [ipaddr, macaddr] 32 return dic 33 34 if __name__ == '__main__': 35 data = getIP() 36 nics = genIP(data) 37 print parseIP(nics)
第三种方式实现(正则表达式):
1 #!/usr/bin/python 2 #encoding: utf-8 3 4 from subprocess import Popen, PIPE 5 import re 6 7 def getIfconfig(): 8 p = Popen(['ifconfig'], stdout = PIPE) 9 data = p.stdout.read().split('\n\n') 10 return [i for i in data if i and not i.startswith('lo')] 11 12 def parseIfconfig(data): 13 dic = {} 14 # re.M 多行模式,改变'^'和'$'的行为 15 for line in data: 16 re_devname = re.compile(r'(\w+).*Link encap', re.M) 17 re_macaddr = re.compile(r'HWaddr\s([0-9A-F:]{17})', re.M) 18 re_ipaddr = re.compile(r'inet addr:([\d\.]{7,15})', re.M) 19 devname = re_devname.search(line) 20 mac = re_macaddr.search(line) 21 ip = re_ipaddr.search(line) 22 if devname: 23 devname = devname.group(1) 24 else: 25 devname = '' 26 27 if mac: 28 mac = mac.group(1) 29 else: 30 mac = '' 31 32 if ip: 33 ip = ip.group(1) 34 else: 35 ip = '' 36 dic[devname] = [mac, ip] 37 return dic 38 39 if __name__ == '__main__': 40 data = getIfconfig() 41 print parseIfconfig(data)
实验结果:
{'eth1': ['00:0C:29:18:1C:7F', '172.16.254.8'], 'eth0': ['00:0C:29:18:1C:75', '192.168.0.8']}