Linux环境下使用Python获取WiFi接口列表的最简方法
在Linux系统中用Python获取WiFi接口列表的方法
方法1:无第三方依赖的纯Python实现(无需额外安装)
直接利用Linux系统调用,通过Python标准库的socket和fcntl模块,检查接口是否支持无线扩展:
import socket import fcntl import struct def get_wifi_interfaces(): wifi_ifaces = [] # 从/proc/net/dev读取所有网络接口 with open('/proc/net/dev', 'r') as f: interfaces = [line.split(':')[0].strip() for line in f.readlines()[2:]] SIOCGIWNAME = 0x8B01 # 标识无线接口的ioctl命令 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for iface in interfaces: try: # 尝试获取接口的无线属性,成功则判定为WiFi接口 buf = bytearray(32) fcntl.ioctl(sock.fileno(), SIOCGIWNAME, struct.pack('i32s', len(buf), iface.encode('utf-8'))) wifi_ifaces.append(iface) except IOError: # 非无线接口会抛出错误,直接跳过 continue return wifi_ifaces # 调用示例 print(get_wifi_interfaces())
方法2:使用第三方库netifaces(API更简洁)
先安装依赖库:
pip install netifaces
结合系统调用实现检测:
import netifaces import socket import fcntl import struct def get_wifi_interfaces(): wifi_ifaces = [] SIOCGIWNAME = 0x8B01 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for iface in netifaces.interfaces(): try: buf = bytearray(32) fcntl.ioctl(sock.fileno(), SIOCGIWNAME, struct.pack('i32s', len(buf), iface.encode('utf-8'))) wifi_ifaces.append(iface) except IOError: continue return wifi_ifaces print(get_wifi_interfaces())
方法3:执行Shell命令(代码量最少)
依赖系统预装的iw工具,直接解析命令输出:
import subprocess def get_wifi_interfaces(): result = subprocess.run(['iw', 'dev'], capture_output=True, text=True) interfaces = [] # 从输出中提取接口名 for line in result.stdout.splitlines(): if line.strip().startswith('Interface'): interfaces.append(line.strip().split()[1]) return interfaces print(get_wifi_interfaces())
总结
- 无依赖需求选方法1,完全基于Python标准库实现;
- 追求代码极简选方法3,但依赖系统
iw工具; - 偏好第三方库API风格选方法2。
内容的提问来源于stack exchange,提问作者tamirg
相关产品推荐
相关产品推荐

