收集服务器网卡和IP信息

收集服务器网卡和IP信息

Python2环境

#!/usr/bin/python2
# -*- coding:utf-8 -*-
import os,sys
import socket, fcntl, struct

def get_devs():
    data = os.popen("ifconfig |awk '{print $1}' |grep -Ei 'eth[0-9]{1}|bond' |sed 's/:$//g'").read()
    return data

def get_ips(ifname):  
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])  

if __name__ == '__main__':
    dic = {}
    devs_info = get_devs()
    for item in devs_info.split():
        try:
            ip = get_ips(item)
        except IOError, e:
            #print("Error -> %s." % e)
            continue
        dic[item] = ip
    #print(len(dic))
    for k in dic:
        print("%s --> %s" % (k, dic[k]))

 

Python3环境

#!/usr/bin/python3
# -*- coding:utf-8 -*-
import netifaces  
ipList = []
for dev in netifaces.interfaces():
    if 2 in netifaces.ifaddresses(dev):
        ip=netifaces.ifaddresses(dev)[2][0]['addr']
        if ip not in ipList and ip != '127.0.0.1':
            ipList.append(ip)
print(ipList)

  

posted @ 2017-05-05 15:18  lixin[at]hitwh  阅读(368)  评论(0编辑  收藏  举报