我正在尝试对我的adrese.txt文件中的地址执行nslookup,我想将它们保存为.csv。目前我最大的问题是它只对一个地址进行nslookup而不是全部。它只退出0,在我的文件中只有一个地址。我是python的新手,不知道如何解决它。另外用输出文件中的csv替换.txt也不错。
编辑:地址从文本文件中获取,第二部分是问题,不知道为什么
import subprocess
f = open("adrese.txt")
next = f.read()
ip=[]
while next != "":
ip.append(next)
next = f.read()
file_ = open('nslookup.txt', 'w')
for i in ip:
process = subprocess.Popen(["nslookup", i], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.communicate()[0]
file_.write(output)
file_.close()
答案 0 :(得分:0)
之所以这样做是因为while next != ""
没有按照您的意愿行事。
相反,请考虑一下:
import subprocess
with open('adrese.txt') as i, open('nslookup.txt', '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')
答案 1 :(得分:0)
您实际上没有遍历adrese.txt中的所有条目
ip = []
f = open("adrese.txt")
for line in f:
ip.append(line)
f.close()
file_ = open('nslookup.txt', 'w')
for i in ip:
process = subprocess.Popen(["nslookup", i], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.communicate()[0]
file_.write(output)
file_.close()
答案 2 :(得分:0)
您可以使用 check_call 并将标准输出直接重定向到文件:
import subprocess
with open('adrese.txt') as f, open('nslookup.txt', 'w') as out:
for line in map(str.rstrip, f):
if line: # skips empty lines
subprocess.check_call(["nslookup", line],
stdout=out)
你永远不会使用 stderr 所以没有点捕获它,如果有任何非零退出状态,你可以捕获CalledProcessError
:
import subprocess
with open('adrese.txt') as f, open('nslookup.txt', 'w') as out:
for line in map(str.rstrip, f):
if line: # skips empty lines
try:
subprocess.check_call(["nslookup", line],
stdout=out)
except subprocess.CalledProcessError:
pass