6

我正在尝试在 Windows 7 上编写一个 Python 脚本,它读取命令的输出ipconfig /displaydns并尝试从输出中获取一些值。

的输出ipconfig /displaydns"是这样的,

Windows IP Configuration

9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.

Record Name . . . . . : 9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.
Record Type . . . . . : 1
Time To Live  . . . . : 294
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 127.0.0.16

我正在获取此输出并将其保存在一个变量中,如下所示,

output = subprocess.check_output("ipconfig /displaydns", shell=True)

当我打印“输出”时,我得到以下信息

b'\r\nWindows IP Configuration\r\n\r\n   9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.\r\n    ----------------------------------------\r\n    Record Name . . . . . : 9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.\r\n    Record Type . . . . . : 1\r\n    Time To Live  . . . . : 289\r\n    Data Length . . . . . : 4\r\n    Section . . . . . . . : Answer\r\n    A (Host) Record . . . : 127.0 .0.16\r\n\r\n\r\n'

从这个输出中,我对分别为 和 的值A (Host) Record感兴趣。Record Name127.0.0.169.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.

我将如何在 Python 中做到这一点?

4

1 回答 1

16
import subprocess
output = subprocess.check_output("ipconfig /displaydns", shell=True)
result = {}
for row in output.split('\n'):
    if ': ' in row:
        key, value = row.split(': ')
        result[key.strip(' .')] = value.strip()

print(result)
print(result['A (Host) Record'])

给出:

{'A (Host) Record': '127.0 .0.16', 'Data Length': '4', 'Section': 'Answer', 'Record Name': '9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.', 'Time To Live': '289', 'Record Type': '1'}
127.0 .0.16

另一种解决方案是:(当我在脑海中想到这个时,我认为它会更紧凑.. 它不是但无论如何,这是调用外部命令的另一种方式,您可以在其中控制错误和输出(你可以区分两者))

import subprocess
cmdpipe = subprocess.Popen("ipconfig /displaydns", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
result = {}
for row in cmdpipe.stdout.readline():
    if ': ' in row:
        key, value = row.split(': ')
        result[key.strip(' .')] = value.strip()

# You need to close the file handles, as they will stay open "forever" otherwise.
cmdpipe.stdout.close()
cmdpipe.stderr.close()

print(result)
print(result['A (Host) Record'])

我还要补充一点,使用shell=True 可能很危险,尤其是与用户输入结合使用时。它确实添加了一些“隐藏的魔法”,使一些事情变得更容易或更用户自然。但在大多数情况下,您会想要这样做subprocess.Popen(["ipconfig", "/displaydns"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

于 2013-04-23T17:19:33.910 回答