我有一个主机名/ IP地址列表,我的脚本从文本文件中获取了每个项目,并将它们作为列表存储在nodes
变量中。
我想对每个主机执行ping操作并将结果输出到一个文本文件。我可以用一个主机来做,但是在理解如何遍历列表时遇到了麻烦。
我看过Stackoverflow上的其他文章,但是大多数文章使用的是OS模块,已经过时了。
我的代码:
#!/usr/local/bin/python3.6
import argparse
import subprocess
parser = argparse.ArgumentParser(description="Reads a file and pings hosts by line.")
parser.add_argument("filename")
args = parser.parse_args()
# Opens a text file that has the list of IP addresses or hostnames and puts
#them into a list.
with open(args.filename) as f:
lines = f.readlines()
nodes = [x.strip() for x in lines]
# Opens the ping program
ping = subprocess.run(
["ping", "-c 1", nodes[0]],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Captures stdout and puts into a text file.
with open('output.txt', 'w') as f:
print(ping.stdout.decode(), file=f)
f.close()
答案 0 :(得分:0)
您可以像这样直接遍历节点列表:
with open(args.filename) as f:
lines = f.readlines()
nodes = [x.strip() for x in lines]
with open('output.txt', 'w') as f:
for node in nodes:
# Opens the ping program
ping = subprocess.run(
["ping", "-c 1", node],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Captures stdout and puts into a text file.
print(ping.stdout.decode(), file=f)
请注意,您还可以直接在输入文件上进行迭代,该输入文件比使用readlines()
更“ Pythonic”:
with open(args.filename,'r') as infile, open('output.txt', 'w') as outfile:
for line in infile:
node = line.strip()
# Opens the ping program
ping = subprocess.run(
["ping", "-c 1", node],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Captures stdout and puts into a text file.
print(ping.stdout.decode(), file=outfile)
请注意,这未经测试,但是看不到任何明显的错误。
答案 1 :(得分:-1)
只需像这样遍历节点列表:
for i in nodes:
ping = subprocess.run(
["ping", "-c 1", i],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
希望它会有所帮助:)