简体   繁体   English

如何使用Python获取默认网关IP?

[英]How can I get the default gateway IP with Python?

I want to get the IP of the default gateway (internal router IP) using Python. 我想使用Python获取默认网关(内部路由器IP)的IP。 I'm really new to Python so not sure how this works. 我是Python的新手,所以不确定它是如何工作的。

I know you can get the IP of your machine with: 我知道你可以通过以下方式获得机器的IP:

import socket
internal_ip = socket.gethostbyname(socket.gethostname())
print internal_ip

So I'm thinking it must be something similar? 所以我认为它必须是类似的东西?

On Windows, you should use WMI along with proper query to lookup properties of an object (eg network devices). 在Windows上,您应该使用WMI以及正确的查询来查找对象的属性(例如,网络设备)。 The following Python code prints IPv4 and default gateway addresses on my Windows 7 machine: 以下Python代码在我的Windows 7计算机上打印IPv4和默认网关地址:

Code: 码:

import wmi

wmi_obj = wmi.WMI()
wmi_sql = "select IPAddress,DefaultIPGateway from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
wmi_out = wmi_obj.query( wmi_sql )

for dev in wmi_out:
    print "IPv4Address:", dev.IPAddress[0], "DefaultIPGateway:", dev.DefaultIPGateway[0]

Output: 输出:

IPv4Address: 192.168.0.2 DefaultIPGateway: 192.168.0.1

You can find more details and tricks of performing WMI operations on network devices on this page . 您可以在此页面上找到有关在网络设备上执行WMI操作的更多详细信息和技巧。

For Linux, PyNetInfo as suggested on this page would be a good approach. 对于Linux, PyNetInfo的建议在这个页面将是一个不错的办法。 Although on Linux you can get around having to depend on an additional module by reading PROC entries among other import os; os.system(...) 虽然在Linux上你可以通过读取其他import os; os.system(...) PROC条目来依赖于一个额外的模块import os; os.system(...) import os; os.system(...) tricks. import os; os.system(...)技巧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM