Python脚本中的ping请求失败

时间:2012-05-08 15:12:20

标签: python-2.7 ping

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

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

我已将上面显示的地址包含在两次(在文件中)并尝试ping。对我做错了什么的想法 - 我是一个蟒蛇新手,所以要温柔。


这是我的剧本:

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)

2 个答案:

答案 0 :(得分:2)

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

  

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

您需要在致电\n之前删除PopenHow can I remove (chomp) a newline in Python?

答案 1 :(得分:1)

很少有评论:

  1. 强烈建议不要使用readlines(),因为它会将整个文件加载到内存中。
  2. 我建议使用Generator,以便在每一行上执行rstrip,然后ping服务器。
  3. 无需使用file.close - 您可以使用带有它的语句
  4. 您的代码应如下所示:

    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)