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

3

你好,我想使用Python获取默认网络接口。 在查找过程中,我得知可以使用pynetinfo来实现。但是,pynetinfo似乎无法在Python3上使用。 是否有其他方法可以替代pynetinfo


“默认”是什么意思?在发送数据包时,内核根据路由表和目标IP地址决定将数据包放置在哪个接口上。你所说的“默认”,是指将数据包中继到“默认网关”的接口吗? - micromoses
是的,micromosesless。非常感谢您的回复。“默认网关”是我想表达的意思。能帮我一个忙吗? - Captain Kidd
你想在Python中模拟 ip route list | grep default | cut -d ' ' -f3 吗? - jfs
3个回答

5
使用 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()

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

在这个例子中,所有流向网络10.200.9.0/24、10.121.0.0/25和10.122.0.0/25的流量分别通过eth1、eth2和eth3进行广播,其余的数据包则使用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

2
出于好奇,你为什么要检查 or not int(flags, 16) & 2 - Juicy

0

两个提供的答案都没有涉及到Windows。 在Windows中,我建议使用PowerShell。

下面的脚本提供了默认网络接口(即路由流量到0.0.0.0/0的接口)的源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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接