MHibbin
MHibbin

Reputation: 1185

Failed ping request in Python script

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)

Upvotes: 1

Views: 2769

Answers (2)

asafm
asafm

Reputation: 921

Few comments:

  1. Using readlines() is highly not recommended as it will load the entire file into memory.
  2. I suggest using Generator in order to perform rstrip on each line and then pinging the server.
  3. No need to use file.close - you can use with statement that does it for you

Your code should look like this:

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)  

Upvotes: 1

Eli Acherkan
Eli Acherkan

Reputation: 6411

Looks like the line variable contains a linebreak at the end (except for the last line of the file). From the Python tutorial:

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.

You need to strip the \n before calling Popen: How can I remove (chomp) a newline in Python?

Upvotes: 2

Related Questions