收集服务器网卡和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)

  

作者:Standby一生热爱名山大川、草原沙漠,还有妹子
出处:http://www.cnblogs.com/standby/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/standby/p/6813159.html