1

我有一个 python 脚本想要 ping 一些(相当多!)主机。我已将其设置为读取 hosts.txt 文件的内容作为要在脚本中 ping 的主机。奇怪的是,对于前几个地址(无论它们是什么),我收到以下错误:

Ping request could not find host 66.211.181.182. Please check the name and try again.

我已经两次(在文件中)包含了上面显示的地址,它会尝试 ping。关于我做错了什么的任何想法 - 我是一个 python 新手,所以要温柔。


这是我的脚本:

import subprocess

hosts_file = open("hosts.txt","r")
lines = hosts_file.readlines()

for line in lines:
    ping = subprocess.Popen(
        ["ping", "-n", "1",line],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )
    out, error = ping.communicate() 
    print out
    print error
hosts_file.close()

这是我的 hosts.txt 文件:

66.211.181.182
178.236.5.39
173.194.67.94
66.211.181.182

以下是上述测试的结果:

Ping request could not find host 66.211.181.182
. Please check the name and try again.


Ping request could not find host 178.236.5.39
. Please check the name and try again.


Ping request could not find host 173.194.67.94
. Please check the name and try again.



Pinging 66.211.181.182 with 32 bytes of data:
Request timed out.

Ping statistics for 66.211.181.182:
    Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)
4

2 回答 2

2

看起来line变量在末尾包含一个换行符(文件的最后一行除外)。来自Python 教程

f.readline()从文件中读取一行;换行符 ( \n) 留在字符串的末尾,如果文件不以换行符结尾,则仅在文件的最后一行省略。

您需要\n在调用之前剥离Popen如何在 Python 中删除(chomp)换行符?

于 2012-05-08T15:20:06.437 回答
1

几点评论:

  1. 强烈不推荐使用 readlines() ,因为它会将整个文件加载到内存中。
  2. 我建议使用 Generator 以便在每一行上执行 rstrip,然后 ping 服务器。
  3. 无需使用 file.close - 您可以使用为您执行此操作的 with 语句

您的代码应如下所示:

import subprocess
def PingHostName(hostname):
    ping=subprocess.Popen(["ping","-n","1",hostname],stdout=subprocess.PIPE
                  ,stderr=subprocess.PIPE)
    out,err=ping.communicate();
    print out
    if err is not None: print err

with open('C:\\myfile.txt') as f:
    striped_lines=(line.rstrip() for line in f)
    for x in striped_lines: PingHostName(x)  
于 2012-05-10T12:02:36.380 回答