2014-03-19 46 views
1

我知道這個腳本在這裏曾經討論過,但我仍然無法正確運行。問題是逐行讀取文本文件。在舊腳本traceroute multiple hos python。 (逐行讀取.txt)

while host: 
    print host 

使用,但使用這種方法程序崩潰,所以我決定將它更改爲

for host in Open_host: 
host = host.strip() 

,但使用這個腳本只給出.txt文件的最後一行的結果。有人可以幫助我使它工作嗎? 下sript:

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

回答

0

我假設你只有在你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() 
+0

感謝名單,現在它正在工作 – Tomas