python - 在 python 上查找 Windows 和 Linux 的默认网关地址

标签 python networking gateway

我想将我的默认网关保存在变量中以供将来使用,例如打印它,或向它发送 ping... 我希望代码能够在 Windows 和 Linux 上运行,所以我编写了以下代码:

import os
if os.name == "Linux":
    dgw = os.system('ip r | grep default | awk {"print $3"}')
    print dgw
if os.name == "Windows":
    dgw = os.system('ifconfig | findstr /i "Gateway"')
    print dgw

但是 dgw 变量没有保存我的默认网关...

Python 2.7

最佳答案

首先,Windows 的os.name'nt',Linux 的os.name'posix'

documentation 中也强调了这一点:

The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.

如果您想定位更具体的平台,请使用 sys.platform是更好的选择。

其次,使用netifaces模块适用于 Windows 和 Linux:

import netifaces
gateways = netifaces.gateways()
default_gateway = gateways['default'][netifaces.AF_INET][0]
print(default_gateway)

您可以使用pip install netifaces进行安装。这种方法的好处是您不需要区分 Windows 和 Linux 之间的方法。

关于python - 在 python 上查找 Windows 和 Linux 的默认网关地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53902519/

相关文章:

python - 显式关闭文件重要吗?

python - 在python上输入()后自动重新启动程序

python - Tornado websocket 日志记录

linux - 强制原始数据包通过 iptables

java - 如何为 Web 应用程序创建文件服务器

c++ - 如何使用 libevent 在两个端点之间进行读写的示例?

angularjs - *** process.env.ENV未定义,假设env为 'prod'

spring - 使用 SpringBoot、Gateway 和 SpringFox Swagger 在微服务中集中 Swagger

java - Spring 集成: How to set up void outbound gateway methods

Python 网格数据 网格网格