使用Python对多个主机进行traceroute(逐行读取.txt文件)

1 投票
1 回答
893 浏览
提问于 2025-04-17 22:55

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

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

1 个回答

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

撰写回答