参考CSDN博主「Kwoky」的https://blog.csdn.net/Kwoky/article/details/84858997的简介:
psutil是一个跨平台库(http://pythonhosted.org/psutil/)能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要用来做系统监控,性能分析,进程管理。它实现了同等命令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等。目前支持32位和64位的Linux、Windows、OS X、FreeBSD和Sun Solaris等操作系统.
import socket
import psutil
def classify_ip_by_network_type():
ip_info = {}
# 获取所有网络接口信息
network_interfaces = psutil.net_if_addrs()
for interface, addresses in network_interfaces.items():
for address in addresses:
# 检查是否为IPv4地址
if address.family == socket.AF_INET:
#检查是否为IPv6地址
#if address.family == psutil.AF_LINK:
# print(address.family)
ip = address.address
network_type = psutil.net_if_stats()[interface].isup
if network_type:
network_type = "Up" # 网络接口处于活动状态
else:
network_type = "Down" # 网络接口处于非活动状态
if network_type not in ip_info:
ip_info[network_type] = []
ip_info[network_type].append((interface, ip))
return ip_info
# 获取IP地址和对应的网络接口类型
ip_info = classify_ip_by_network_type()
for network_type, ip_list in ip_info.items():
print(f"网络接口状态: {network_type}")
for interface, ip in ip_list:
print(f"网络接口: {interface}, IP地址: {ip}")
运行结果
网络接口类型: Up
网络接口: 以太网, IP地址: 10.12.135.74
网络接口: VMware Network Adapter VMnet1, IP地址: 192.168.189.1
网络接口: VMware Network Adapter VMnet8, IP地址: 192.168.199.1
网络接口: vEthernet (Default Switch), IP地址: 172.26.160.1
网络接口: Loopback Pseudo-Interface 1, IP地址: 127.0.0.1
网络接口类型: Down
网络接口: WLAN, IP地址: 169.254.72.113
网络接口: 本地连接* 9, IP地址: 169.254.208.9
网络接口: 本地连接* 10, IP地址: 169.254.118.33