我知道这个脚本之前在这里讨论过,但我仍然无法正常运行它。问题是逐行读取文本文件。在旧脚本中
while host:
print host
用过,但是用这个方法程序崩溃了,所以决定改成
for host in Open_host:
host = host.strip()
但是使用这个脚本只会给出 .txt 文件中最后一行的结果。有人可以帮我让它工作吗?下面的脚本:
# import subprocess
import subprocess
# Prepare host and results file
Open_host = open('c:/OSN/host.txt','r')
Write_results = open('c:/OSN/TracerouteResults.txt','a')
host = Open_host.readline()
# loop: excuse trace route for each host
for host in Open_host:
host = host.strip()
# execute Traceroute process and pipe the result to a string
Traceroute = subprocess.Popen(["tracert", '-w', '100', host],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
hop = Traceroute.stdout.readline()
if not hop: break
print '-->',hop
Write_results.write( hop )
Traceroute.wait()
# Reading a new host
host = Open_host.readline()
# close files
Open_host.close()
Write_results.close()