netifaces
1. introduction
在Linux系统中,我们可以使用ip addr、ifconfig、route等命令查看系统网络等相关配置。也可以在查询结果中使用正则表达式,管道,awk等处理提取相关信息。
在python中可以使用第三方库netifaces
获取有关网络接口及状态的信息,如ip地址,MAC地址等。
2. install
2.1 source install
tar xvzf netifaces-0.10.4.tar.gz
cd netifaces-0.10.4
sudo python setup.py install
2.2 pip install
pip3 install netifaces
3. employ
3.1 获取网络接口名
@staticmethod
def get_local_interfaces() -> list:
"""
description: 获取本机网络接口名
:return: ['lo', 'enp3s0']
"""
interfaces = netifaces.interfaces()
print(interfaces)
return interfaces
3.2 根据接口名获取网络信息
@staticmethod
def get_local_info():
"""
description: 根据网络接口名获取网络信息
:return:
"""
interfaces = netifaces.interfaces()
for interface in interfaces:
print(netifaces.ifaddresses(interface))
{
17: [
{
‘addr’: ‘4c:cc:6a:19:6b:53’,
‘broadcast’: ‘ff:ff:ff:ff:ff:ff’
}
],
2: [
{
‘addr’: ‘192.168.7.101’,
‘netmask’: ‘255.255.255.0’,
‘broadcast’: ‘192.168.7.255’
}
],
10: [
{
‘addr’: ‘fe80::5468:5c8c:57c6:b936%enp3s0’,
‘netmask’: ‘ffff:ffff:ffff:ffff::/64’
}
]
}
返回值详解:
- 数据类型:字典
- 与linux系统执行
ifconfig
命令输出结果基本一致,就是对应网卡的详细信息。通过这些信息可以得到期望的ip,mac等信息。 - key值是
netifaces.address_families
中映射的值,例如17对应的是AF_PACKET信息,2对应的是AF_INET也就是IPV4
信息。 - 可以通过映射值直接获取信息。
3.3 映射常量值
@staticmethod
def get_families():
print(netifaces.address_families)
3.4 获取路由信息
@staticmethod
def get_local_gateway():
"""
description: 获取路由信息
:return: {'default': {2: ('192.168.7.254', 'enp3s0')}, 2: [('192.168.7.254', 'enp3s0', True)]}
"""
netifaces.gateways()
4. example
4.1 get local ip
@staticmethod
def get_ip():
interfaces = netifaces.interfaces()
for interface in interfaces:
info = netifaces.ifaddresses(interface)
local_info = info[netifaces.AF_INET][0]
local_ip = local_info['addr']
print(local_ip)
4.2 get local netmask
@staticmethod
def get_netmask():
interfaces = netifaces.interfaces()
for interface in interfaces:
info = netifaces.ifaddresses(interface)
local_info = info[netifaces.AF_INET][0]
local_netmask = local_info['netmask']
print(local_netmask)
4.3 get gateway ip
@staticmethod
def get_gateway():
gateway = netifaces.gateways().get(netifaces.AF_INET)
local_gateway = gateway[0][0]
print(local_gateway)