使用Python查看ip,psutil,netifaces

1.Linux下获取网卡和其对应的IP地址,需要先安装psutil模块

import psutil
 
 
def get_net_card():
    net_card_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':
                net_card_info.append((k, item[1]))
    return net_card_info
 
 
if __name__ == '__main__':
    print(get_net_card())
#获取linux的ip信息
psutil.net_if_addrs()

2.使用netifaces库获取ip信息

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:               LinuxBashShellScriptForOps:getNetworkStatus.py
User:               Guodong
Create Date:        2016/11/2
Create Time:        16:20
show Windows or Linux network Nic status, such as MAC address, Gateway, IP address, etc
# python getNetworkStatus.py
Routing Gateway:               10.6.28.254
Routing NIC Name:              eth0
Routing NIC MAC Address:       06:7f:12:00:00:15
Routing IP Address:            10.6.28.28
Routing IP Netmask:            255.255.255.0
 """
import os
import sys
 
try:
    import netifaces
except ImportError:
    try:
        command_to_execute = "pip install netifaces || easy_install netifaces"
        os.system(command_to_execute)
    except OSError:
        print "Can NOT install netifaces, Aborted!"
        sys.exit(1)
    import netifaces
 
routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]
 
for interface in netifaces.interfaces():
    if interface == routingNicName:
        # print netifaces.ifaddresses(interface)
        routingNicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
        try:
            routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
            # TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
            routingIPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
        except KeyError:
            pass
 
display_format = '%-30s %-20s'
print display_format % ("Routing Gateway:", routingGateway)
print display_format % ("Routing NIC Name:", routingNicName)
print display_format % ("Routing NIC MAC Address:", routingNicMacAddr)
print display_format % ("Routing IP Address:", routingIPAddr)
print display_format % ("Routing IP Netmask:", routingIPNetmask)
2.1地址类型编码

Netifaces定义了接口地址类型字典,你可以很方便的查询各类地址类型对应的地址类型编码,在后面的介绍中,我们会发现查询结果仅显示接口地址类型编码,可以通过address_families查询地址编码的字符串表示形式。

>>> import netifaces  
>>> netifaces.address_families  
{0: 'AF_UNSPEC', 1: 'AF_FILE', 2: 'AF_INET', 3: 'AF_AX25', 4: 'AF_IPX',   
5: 'AF_APPLETALK', 6: 'AF_NETROM', 7: 'AF_BRIDGE', 8: 'AF_ATMPVC', 9: 'AF_X25',   
10: 'AF_INET6', 11: 'AF_ROSE', 12: 'AF_DECnet', 13: 'AF_NETBEUI', 14: 'AF_SECURITY',   
15: 'AF_KEY', 16: 'AF_NETLINK', 17: 'AF_PACKET', 18: 'AF_ASH', 19: 'AF_ECONET',   
20: 'AF_ATMSVC', 22: 'AF_SNA', 23: 'AF_IRDA', 24: 'AF_PPPOX', 25: 'AF_WANPIPE',   
31: 'AF_BLUETOOTH', 34: 'AF_ISDN'}  
2.2接口查询
>>> netifaces.interfaces()  
['lo', 'eth0', 'eth1']  

通过interfaces()函数接口,可以很容易的获取系统当前的接口列表。

2.3接口配置查询

我们获取了系统的接口信息后,就可以继续查询指定接口的地址配置信息。

>>> netifaces.ifaddresses('eth0')  
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:0c:29:3e:6b:c8'}],   
2: [{'broadcast': '10.220.33.255', 'netmask': '255.255.255.0', 'addr': '10.220.33.101'}],   
10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::20c:29ff:fe3e:6bc8%eth0'}]}  

使用ifaddresses()接口,可以这么容易的获取接口的地址配置信息,返回的信息以字典的形式返回。每一项都指向了一个特定的地址簇配置,如

2: [{'broadcast': '10.220.33.255', 'netmask': '255.255.255.0', 'addr': '10.220.33.101'}]  

地址类型为2,查询address_families,我们可以知道它是AF_INET的类型,是关于IPv4的配置。在你实际使用中,不要直接使用2这种魔数,实际上该模块已经定义了一些常量,正确的用法,我们可以参考下面的例子:

>>> netifaces.ifaddresses('eth0')[netifaces.AF_INET]  
[{'broadcast': '10.220.33.255', 'netmask': '255.255.255.0', 'addr': '10.220.33.101'}]  
2.4网关和路由信息查询

为了方便使用,使用‘default’可以引用缺省网关配置,如果查询特定地址的网关信息,也非常容易,由于查询结果是字典形式表示,输入对应的接口地址类型,就可以查询指定的结果:

>>> netifaces.gateways()  
{'default': {2: ('10.220.33.1', 'eth0')}, 2: [('10.220.33.1', 'eth0', True)]}  
>>>  
>>> netifaces.gateways()[netifaces.AF_INET]  
[('10.220.33.1', 'eth0', True)]  
2.5源码实例:获取本机IP
import netifaces
 
def get_most_likely_ip():
    for interface_name in netifaces.interfaces():
        if interface_name.startswith('lo'):
            continue
        # TODO: continue if network interface is down
        #如果网络接口关闭,继续
        addresses = netifaces.ifaddresses(interface_name)
        if netifaces.AF_INET in addresses:
            for item in addresses[netifaces.AF_INET]:
                if 'addr' in item:
                    logger.debug('Found likely IP {0} on interface {1}'.format(item['addr'], interface_name))
                    return item['addr']
                    # well, actually the interface could have more IP's... But for now we assume that the IP
                    # we want is the first in the list on the IF.
                    #实际上,接口可以有更多的IP…但是现在我们假设我们想要的IP是if列表中的第一个。
 
    default_ip = '127.0.0.1'
    logger.warning('Count not detect likely IP, returning {0}'.format(default_ip))
    return '127.0.0.1'

参考资料:https://blog.youkuaiyun.com/u012206617/article/details/92677788

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值