1

我知道这个脚本之前在这里讨论过,但我仍然无法正常运行它。问题是逐行读取文本文件。在旧脚本中

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() 
4

1 回答 1

0

我假设您的host.txt文件中只有两个或三个主机。Open_host.readline()罪魁祸首是在循环之前和每次迭代结束时对您进行的调用,导致您的脚本跳过列表中的第一个主机,以及两个主机中的一个。只需删除那些就可以解决您的问题。

这是代码,更新了一点以更pythonic:

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()
于 2014-03-19T09:18:09.333 回答