在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做到这一点?理想情况下在一行?
答案 0 :(得分: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
答案 1 :(得分:0)
这会给你ipconfig命令输出:
导入子流程
(out,err)= subprocess.Popen([&#34; ipconfig&#34;],stdout = subprocess.PIPE,shell = True).communicate()
现在只需解析str就可以将IP仅列入列表。