【问题标题】:How to list all the IP addresses defined on a Windows system with python?如何使用python列出Windows系统上定义的所有IP地址?
【发布时间】:2014-10-09 05:46:47
【问题描述】:

在Windows7机器上我添加了一些虚拟IP地址,所以ipconfig的输出如下:

Windows IP Configuration

Ethernet adapter LAN-Verbindung:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::2d27:f07a:a617:b01e%11
   IPv4 Address. . . . . . . . . . . : 172.16.5.23
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   IPv4 Address. . . . . . . . . . . : 172.16.5.161
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   IPv4 Address. . . . . . . . . . . : 172.16.5.162
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   IPv4 Address. . . . . . . . . . . : 172.16.5.163
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 172.16.5.1

Ethernet adapter VirtualBox Host-Only Network:

----

使用standard-python,仅使用标准库,我如何获得所有这些 IPv4 地址的列表,即我想要一些 python 代码返回以下信息:

172.16.5.23
172.16.5.161
172.16.5.162
172.16.5.163

如何用 python 做到这一点?最好是一行?

【问题讨论】:

  • subprocess 和 re 可以工作,但需要全部 3 行
  • 是的,我可能需要走这条路。我希望有一种方法可以避免子进程...
  • 如果使用 check_output 实际上只有两行

标签: python windows networking ip


【解决方案1】:
import subprocess
import re
proc = subprocess.check_output("ipconfig" )
print "\n".join(re.findall(r"(?<=IPv4 Address. . . . . . . . . . . : )(\d+\.\d+\.\d+\.\d+)",proc))

一个例子:

s = """
Ethernet adapter LAN-Verbindung:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::2d27:f07a:a617:b01e%11
   IPv4 Address. . . . . . . . . . . : 172.16.5.23
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   IPv4 Address. . . . . . . . . . . : 172.16.5.161
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   IPv4 Address. . . . . . . . . . . : 172.16.5.162
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   IPv4 Address. . . . . . . . . . . : 172.16.5.163
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 172.16.5.1
   """
In [13]: print "\n".join(re.findall(r"(?<=IPv4 Address. . . . . . . . . . . : )(\d+\.\d+\.\d+\.\d+)",s))
172.16.5.23
172.16.5.161
172.16.5.162
172.16.5.163

【讨论】:

    【解决方案2】:

    这将为您提供 ipconfig 命令输出:

    导入子流程

    (out,err) = subprocess.Popen(["ipconfig"], stdout=subprocess.PIPE, shell=True).communicate()

    现在只需解析 str 以仅获取列表中的 IP。

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2022-12-09
      • 1970-01-01
      相关资源
      最近更新 更多