有没有一种方法可以使用python3在本地获取默认网络接口?

时间:2014-01-03 16:30:41

标签: python networking routing python-3.3

您好我想使用Python获取默认网络接口。 谷歌之后,我得到pynetinfo可以做到这一点。但pynetinfo似乎无法在Python3上运行。 还有另一种方法来代替pynetinfo吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()

答案 2 :(得分: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()
相关问题