你好,我想使用Python获取默认网络接口。
在查找过程中,我得知可以使用pynetinfo
来实现。但是,pynetinfo
似乎无法在Python3上使用。
是否有其他方法可以替代pynetinfo
?
你好,我想使用Python获取默认网络接口。
在查找过程中,我得知可以使用pynetinfo
来实现。但是,pynetinfo
似乎无法在Python3上使用。
是否有其他方法可以替代pynetinfo
?
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()
如果您正在使用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
or not int(flags, 16) & 2
? - Juicy两个提供的答案都没有涉及到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()
ip route list | grep default | cut -d ' ' -f3
吗? - jfs