是否有使用python3获取本地默认网络接口的方法?

问题描述 投票:2回答:3

[嗨,我想使用Python获取默认的网络接口。google之后,我得到了pynetinfo可以做到这一点。但是pynetinfo似乎不适用于Python3。还有另一种方法可以代替pynetinfo吗?

python networking routing python-3.3
3个回答
5
投票

如果使用Linux,则可以直接在/proc/net/route上检查路由表。该文件包含系统的路由参数,下面是一个示例:

Iface   Destination Gateway     Flags   RefCnt  Use Metric  Mask        MTU Window  IRTT
eth1    0009C80A    00000000    0001    0       0   0       00FFFFFF    0   0       0
eth2    0000790A    00000000    0001    0       0   0       0080FFFF    0   0       0
eth3    00007A0A    00000000    0001    0       0   0       0080FFFF    0   0       0
eth0    00000000    FE09C80A    0003    0       0   0       00000000    0   0       0

在此示例中,分别通过eth1,eth2和eth3广播到网络10.200.9.0/24、10.121.0.0/25和10.122.0.0/25的所有流量,其余包使用eth0接口发送到网关10.200。 9.254。所以问题是如何使用Python以编程方式获取此信息?

def get_default_iface_name_linux():
    route = "/proc/net/route"
    with open(route) as f:
        for line in f.readlines():
            try:
                iface, dest, _, flags, _, _, _, _, _, _, _, =  line.strip().split()
                if dest != '00000000' or not int(flags, 16) & 2:
                    continue
                return iface
            except:
                continue

get_default_iface_name_linux() # will return eth0 in our example

4
投票

带有pyroute2

from pyroute2 import IPDB
ip = IPDB()
# interface index:
print(ip.routes['default']['oif'])
# interface details:
print(ip.interfaces[ip.routes['default']['oif']])
# release DB
ip.release()

0
投票

两者提供的答案均不适用于Windows。在Windows中,我建议使用PowerShell。

下面的脚本提供默认网络接口(将流量路由到0.0.0.0/0的I.E.接口)的源IP地址:

from subprocess import check_output
src_ip = check_output((
        "powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy bypass -Command ""& {"
        "Get-NetRoute –DestinationPrefix '0.0.0.0/0' | Select-Object -First 1 | "
        "Get-NetIPAddress | Select-Object -ExpandProperty IPAddress"
        "}"""
    )).decode().strip()
print(src_ip)

与默认网络接口本身相同:

check_output((
    "powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy bypass -Command ""& {"
    "Get-NetRoute –DestinationPrefix '0.0.0.0/0' | Select-Object -First 1 | "
    "Get-NetIPConfiguration"
    "}"""
)).decode().strip()
© www.soinside.com 2019 - 2024. All rights reserved.