【问题标题】:How to select specific text from the output?如何从输出中选择特定文本?
【发布时间】:2018-06-04 21:52:51
【问题描述】:

我正在通过从一个 csv 文件中读取主机名来执行 nslookup,并且我想将 FQDN 写入另一个 csv 文件。

这是我的代码:

import subprocess

with open('csv1.csv', 'r') as i, open('csv2.csv', 'w') as o:
   for line in i:
     if line.strip(): # skips empty lines
        proc = subprocess.Popen(["nslookup", line.strip()],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        o.write('{}\n'.format(proc.communicate(0)))

print('Done')

我面临的问题是,当在 cmd->nslookup 中完成时,它会提供类似的所有详细信息,例如“服务器”、“地址”、“FQDN”和 IP 地址 以下是其中一个主机名的示例:

(b'Server:  anything.na.com\r\nAddress:  10.3.56.7\r\n\r\nName:    ABCD12.na.com\r\nAddress:  10.4.67.8\r\nAliases:  abcd12.na.com\r\n\r\n'

我只想将此处的 FQDN 名称提取到 csv 文件中。

【问题讨论】:

  • nslookup 不太适合集成到其他程序中。如果您有dig,请尝试dig +short。显而易见的解决方案是使用 Python DNS 解析器,但根本不使用外部实用程序;我喜欢dnspython,虽然参考文档有点吓人。

标签: python python-3.x nslookup


【解决方案1】:

只需使用resplit找到您要查找的数据:

import subprocess

with open('csv1.csv', 'r') as i, open('csv2.csv', 'w') as o:
   for line in i:
     if line.strip(): # skips empty lines
        proc = subprocess.Popen(["nslookup", line.strip()],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        stdout_data, stderr_data = proc.communicate(0)
        fqdn = stdout_data.split(b'Server:  ')[1].split(b'\r\n')[0]
        o.write('{}\n'.format(fqdn))

【讨论】:

  • 我正在使用 Python 3.6,它似乎没有该属性。它给了我一个错误:AttributeError: 'tuple' object has no attribute 'split'
  • Popen.communicate() 返回一个元组 (stdout_data, stderr_data)
  • @Gelineau 完美!你能解释一下 stdout_data.split(b'Server: ')[1].split(b'\r\n')[0] -> 为什么我们在这里使用 [1] 和 [0] 以及用于什么语境?它到底是什么分裂?因此,如果我需要删除其他列,那么我只需要更改它。
  • @AlexP。你也可以简要介绍一下:)
  • input_text.split(separator) 使用分隔符拆分 input_text。当使用 [0] 时,我们取第一个分隔符之前的文本。使用 [1] 时,我们将文本放在第一个分隔符之后(如果存在,则在第二个分隔符之前)
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
相关资源
最近更新 更多