我知道这个脚本之前在这里讨论过,但我仍然不能正常运行它。问题是逐行读取文本文件。旧脚本
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()
我假设您的host.txt
文件中只有两个或三个主机。罪魁祸首是在循环之前和每次迭代结束时对Open_host.readline()
的调用,导致脚本跳过列表中的第一个主机和两个主机中的一个。只要把它们去掉,问题就解决了。
下面是代码,更新了一点,使其更python化:
import subprocess
with open("hostlist.txt", "r") as hostlist, open("results.txt", "a") as output:
for host in hostlist:
host = host.strip()
print "Tracing", host
trace = subprocess.Popen(["tracert", "-w", "100", host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
hop = trace.stdout.readline()
if not hop: break
print '-->', hop.strip()
output.write(hop)
# When you pipe stdout, the doc recommends that you use .communicate()
# instead of wait()
# see: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
trace.communicate()