standby

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

  

分类:

技术点:

相关文章:

  • 2021-09-02
  • 2021-11-22
  • 2022-01-18
  • 2021-11-15
  • 2021-05-22
  • 2021-06-01
  • 2021-07-23
猜你喜欢
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2021-12-23
  • 2021-07-13
  • 2021-09-14
  • 2021-11-05
相关资源
相似解决方案