Home:ALL Converter>Failed ping request in Python script

Failed ping request in Python script

Ask Time:2012-05-08T23:12:20         Author:MHibbin

Json Formatter

I have a python script that want to ping a few (quite a few!) hosts. I have set this up to read the contents of a hosts.txt file as the hosts to ping in the script. The odd thing is that I am recieving the following error, for the first few addresses (no matter what they are):

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

I have included the address shown above at twice (within the file) and it attempts a ping. Any thoughts on what I am doing wrong - I am a python newbie, so be gentle.


Here is my script:

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

Here is my hosts.txt file:

66.211.181.182
178.236.5.39
173.194.67.94
66.211.181.182

And here are the results from the above test:

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)

Author:MHibbin,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/10501411/failed-ping-request-in-python-script
Eli Acherkan :

Looks like the line variable contains a linebreak at the end (except for the last line of the file). From the Python tutorial:\n\n\n f.readline() reads a single line from the file; a newline character (\\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.\n\n\nYou need to strip the \\n before calling Popen: How can I remove (chomp) a newline in Python?",
2012-05-08T15:20:06
yy