Python获取多网卡的IP地址的几种方法(Linux系统)

过年之前,有一个任务是将原来的windows工具客户端改写一个Linux版本,对于python来说,很好移植。不过其中有一个很关键的步骤是获取当前设备的ip地址,window版的函数不能直接拿来用了。

本来很简单的一件事,由于公司许多机器的Linux版本不同,机器的网卡数量也不一样,本来在自己的机器测试完没问题,拿给别人一用就出现各种问题,适配完,换了机器又出现新的问题,导致前前后后竟然改了四种方法。

思路无非就是通过获取linux命令的输出结果来解析出每个ip,试过很多命令加正则表达式的组合,实现是肯定可以实现,但是越弄越复杂,感觉不够优雅,而且不能保证适配所有版本的系统,最后竟然在一篇博客发现了一个命令只需要一行代码,当时的心情真的是哭笑不得。这里记录一下,以备不时之需。

命令:

hostname -I

命令输出:

202.196.1.0 202.196.1.1

程序:

def getIPAddrs(self):
    p = Popen("hostname -I", shell=True, stdout=PIPE)
    data = p.stdout.read() # 获取命令输出内容
    data = str(data,encoding = 'UTF-8') # 将输出内容编码成字符串
    ip_list = data.split(' ') # 用空格分隔输出内容得到包含所有IP的列表
    if "\n" in ip_list: # 发现有的系统版本输出结果最后会带一个换行符
        ip_list.remove("\n")
    print(ip_list)
    return ip_list

输出结果:

[202.196.1.0, 202.196.1.1]


之前用的方法(Linux):

 def getIPAddrsV2(self):
     p = Popen("ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'", shell=True, stdout=PIPE)
     data = p.stdout.read()
     data = str(data,encoding = 'UTF-8')
     ip_list = data.split('\n')
     ip_list.remove("")
     ip_list2 = []
     for ip in ip_list:
         if ":" in ip:
             ip_list2.append(ip.split(":")[-1])
         else:
             ip_list2.append(ip)
     print(ip_list2)
     return ip_list2

 def getIPAddrsV3(self):
     import psutil
     netcard_info = []
     info = psutil.net_if_addrs()
     for k, v in info.items():
         for item in v:
             if item[0] == 2 and not item[1] == '127.0.0.1':
                 # netcard_info.append((k, item[1]))
                 netcard_info.append( item[1])
     return netcard_info

 def getIPAddrsV4(self):
     import fcntl
     import struct
     ifname = b'enp0s31f6' # 网卡名字
     ip_list = []
     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack(b'256s', ifname[:15]))[20:24])
     ip_list.append(ip)
     return ip_list

之前用的方法(Windows):

'''获取pc的IPv4地址'''
def getIPAddrs(self):
    ip_list = socket.gethostbyname_ex(socket.gethostname())
    for ips in ip_list:
        if type(ips) == list and len(ips) != 0:
            IPlist = ips
    return IPlist

 def getIPAddrsV2(self):
     p = Popen('ipconfig|findstr IPv4', shell=True, stdout=PIPE)
     data = p.stdout.read().decode(encoding='gb2312')
     IPlist = []
     splitlist = re.split('[\r:]', data)
     for eachpart in splitlist:
         if '.' in eachpart and 'IP' not in eachpart:
             IPlist.append(eachpart.strip())
     return IPlist

 

你可能感兴趣的:(Linux)