Python:获取设备的当前连接类型(Lan、Wifi、移动(sim 卡))

Python: Getting current Connection Type (Lan, Wifi, Mobile(sim card)) of device

我想知道如何获取 python 脚本所在设备的当前连接类型 运行 据我所知,这只能是三种类型。

这可能吗?如果是这样,谁能把我引向正确的方向?因为我找不到可以帮助我的东西。

设备本身是 RaspBerry Pi 4B。

编辑:我还想知道这些设备中的哪些正在用于连接 接口可以“启动”但可能不是用于连接的主要接口。这是为了获取某些函数的布尔值。

我建议使用 psutil.net_if_stats()psutil 是 cross-platform,应该可以在任何设备上正常工作。

  • psutil.net_if_stats()
  • 列出 NIC 设备统计字典
  • 使用 isup=True
  • 过滤设备
  • 查看 Wifi、Lan 或移动设备是否可用(在 linux 中是 wlan0、eth 或 enp - 不确定移动设备)
>>> import psutil
>>> from pprint import pprint

>>> nets = psutil.net_if_stats()
>>> pprint(nets)
{'Bluetooth 네트워크 연결': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=3, mtu=1500),
 'Loopback Pseudo-Interface 1': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1073, mtu=1500),
 'Wi-Fi': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=432, mtu=1500),
 'vEthernet (WSL)': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=4294, mtu=1500),
 '로컬 영역 연결* 1': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500),
 '로컬 영역 연결* 10': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500),
 '이더넷': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=2500, mtu=1500)}

>>> active_nets = {name: net_stat for name, net_stat in nets.items() if net_stat.isup}
>>> pprint(active_nets)
{'Loopback Pseudo-Interface 1': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1073, mtu=1500),
 'Wi-Fi': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=432, mtu=1500),
 'vEthernet (WSL)': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=4294, mtu=1500)}
>>>

要获取地址,psutil.net_if_addrs() 可以提供帮助。

通过这些,我们可以获得活动网卡的名称,以及它的 IP。

from typing import Tuple, List
from socket import AF_LINK, AF_INET, AF_INET6

import psutil


class NetworkInterfaceNotFound(Exception):
    pass


def get_active_nets():
    """
    Get active NIC names.

    Returns:
        Set of active NIC names.
    """

    return {name for name, net in psutil.net_if_stats().items() if net.isup}


def determine_current_nic(*net_names) -> Tuple[str, str, List[str], List[str]]:
    """
    Determine primary active NIC.

    Notes:
        One NIC may have multiple addresses of same family. Thus returning in list.

    Args:
        *net_names: NIC names to look for. NIC priority == item order

    Returns:
        NIC's Name, MAC, IPv4 address list, IPv6 address list
    """

    types = {
        AF_LINK.name: [],
        AF_INET.name: [],
        AF_INET6.name: [],
    }

    active_nets = get_active_nets()
    address_dict = psutil.net_if_addrs()

    matching_name = ""

    for net_name in net_names:

        if net_name in active_nets:
            # now we have the device.
            matching_name = net_name
            break

    else:
        # if none exists, raise
        raise NetworkInterfaceNotFound(f"There's no matching NIC with names {net_names}")

    for address in address_dict[matching_name]:
        types[address.family.name].append(address.address)

    return matching_name, types[AF_LINK.name][0], types[AF_INET.name], types[AF_INET6.name]
    # otherwise, no matching NIC


# ---

if __name__ == '__main__':
    name_, mac, ipv4, ipv6 = determine_current_nic("이더넷", "Wi-Fi", "Bluetooth 네트워크 연결")
    print(name_, mac, ipv4, ipv6)

示例输出:

Wi-Fi **-**-**-**-**-** ['___.___.___.___'] ['____::____:____:____:____']