traceroute多个hos python。(逐行读取.txt)

2024-06-16 11:40:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个脚本以前在这里讨论过,但我还是不能正常运行它。问题是逐行读取文本文件。用旧的字体

while host:
  print host  

被使用,但是使用这个方法的程序崩溃了,所以我决定把它改成

^{pr2}$

但是使用这个脚本只给出.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() 

Tags: andimporttxt脚本hostclosereadlineopen
1条回答
网友
1楼 · 发布于 2024-06-16 11:40:59

我假设您的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()

相关问题 更多 >