有没有一种方法可以使用python3在本地获取默认网络接口?
嗨,我想用Python获得默认的网络接口。 在谷歌之后,我得到了有没有一种方法可以使用python3在本地获取默认网络接口?,python,networking,routing,python-3.3,Python,Networking,Routing,Python 3.3,嗨,我想用Python获得默认的网络接口。 在谷歌之后,我得到了pynetinfo可以做到这一点。但是,pynetinfo似乎不适用于Python3。 是否有另一种方法来代替pynetinfo?如果您使用Linux,您可以直接在/proc/net/route上检查路由表。此文件包含系统的路由参数,以下是一个示例: Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT eth
pynetinfo
可以做到这一点。但是,pynetinfo
似乎不适用于Python3。
是否有另一种方法来代替pynetinfo?如果您使用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
与:
两个提供的答案都不针对Windows。 在Windows中,我建议使用PowerShell 下面的脚本为默认网络接口(即将流量路由到0.0.0.0/0的接口)提供源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()
你说的“默认”是什么意思?当发送数据包时,内核根据路由表,根据给定的目标ip地址决定将数据包放在哪个接口上。您是指将数据包中继到
默认网关的界面中的“默认”吗?是的,微操作。非常感谢您的回复。“默认网关”是我想表达的。能帮我一个忙吗?你想在Python中模拟ip路由列表| grep default | cut-d'-f3
?出于好奇,你为什么要检查或不检查int(flags,16)和2
?
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()