我想将我的默认网关保存在变量中以供将来使用,例如打印它,或向它发送 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/