【问题标题】:Find default gateway address for Windows and Linux on python在 python 上查找 Windows 和 Linux 的默认网关地址
【发布时间】:2019-05-22 23:20:55
【问题描述】:
我想将我的默认网关保存在一个变量中以供将来使用,例如打印它,或者发送一个 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
【问题讨论】:
标签:
python
networking
gateway
【解决方案1】:
首先,Windows 的os.name 是'nt',Linux 是'posix'。
documentation 中也强调了这一点:
导入的操作系统相关模块的名称。当前已注册以下名称:'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 之间的方法。
【解决方案2】:
这是因为 os.system 不返回标准输出。
你应该使用一个子进程。
#For Linux
import subprocess
p = subprocess.Popen(["ip r"], stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()
print out