我试图在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(主机)记录和记录名称的值127.0.0.16和9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.分别.
我怎么用Python做的?
最佳答案
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()
print(result)
print(result['A (Host) Record'])