using text file to get ip address from hostname

Hans Mulder hansmu at xs4all.nl
Sat Sep 15 14:52:39 EDT 2012


On 15/09/12 18:20:42, Dan Katorza wrote:
> בתאריך יום רביעי, 12 בספטמבר 2012 17:24:50 UTC+3, מאת Dan Katorza:
>> hello ,
>>
>>
>>
>> i'm new to Python and i searched the web and could not find an answer for my issue.
>>
>>
>>
>> i need to get an ip address from list of hostnames which are in a textfile.
>>
>>
>>
>> this is what i have so far 
>>
>> --------------------------------------------------------------------------
>>
>> #!/usr/bin/env python
>>
>> #Get the IP Address
>>
>>
>>
>> import socket
>>
>> hostname = 'need it to read from a text file'
>>
>> addr = socket.gethostbyname(hostname)
>>
>> print 'The address of ', hostname, 'is', addr 
>>
>>
>>
>> ---------------------------------------------------------------------------
>>
>>
>>
>> any idea ? 
>>
>> sorry for my english
>>
>>
>>
>> thanks.
> 
> hello again friends,
> thanks for everyone help on this.
> i guess i figured it out in two ways.
> the second one i prefer the most.
> 
> i will appreciate if someone can give me some tips.
> thanks again 
> 
> so...
> -------------------------------------------------------------
> First 
> -------------------------------------------------------------
> #!/usr/bin/env python
> #Get the IP Address
> 
> 
> print("hello, please enter file name here >"),

Instead of printing this string, you can pass it as the
argument to raw_input:

for line in open(raw_input("hello, please enter file name here> ")):

Cosmetically, I'd prefer a space after the '>'.

> import socket

PEP 8 recommends putting all imports at the top of the file, like you
do in your second script.

> for line in open(raw_input()):
>     hostname = line.strip()
>     print("IP address for {0} is {1}.".format(hostname,socket.gethostbyname(hostname)))

To my mind, this line does two things: it finds the IP address and
prints it.  I think it would be more readable to do these on separate
lines:

    ip_address = socket.gethostbyname(hostname)
    print("IP address for {0} is {1}.".format(hostname, ip_address)

This forces you to find a good name for the value returned
by gethostbyname, which I consider a Good Thing (tm).

PEP 8 recommends that lines should not be longer than 80
characters.  Your line is longer than that; splitting it
in two conceptual steps nicely solves that issue as well.

> ------------------------------------------------------------
> second
> ------------------------------------------------------------
> #!/usr/bin/env python
> #Get the IP Address
> 
> import os
> 
> print("Hello, please enter file name here >"),
> FILENAME = raw_input()

PEP 8 recommends all upper case for constants, for example
socket.IPPROTO_IPV6.  The filename here is not a hard-wired
constant, so it should be in lower case.

> if os.path.isfile(FILENAME):

Your first script allowed me to enter "/dev/tty" at the prompt,
and then type a bunch of hostnames and an end-of-file character.
This script reports "FIle is missing or not reasable", because
/dev/tty is not a regular file.  I think the message should be
"File is missing or not readable or not a regular file".

I'm always annoyed when I get an error message with several
"or"s in it.  I prefer programs that figure out which of the
three potential issues is the case, and mention only one cause.

>     print("\nFile Exist!")
>     print("\nGetting ip from host name")
>     print("\n")
>     import socket
>     for line in open (FILENAME):
>         hostname = line.strip()
>         print("IP address for {0} is {1}.".format(hostname,socket.gethostbyname(hostname)))
>     else:
>         print ("\nFinished the operation")
> else:
>     print ("\nFIle is missing or is not reasable"),

You don't want a comma at the end of this line: it messes
up the next shell prompt.

Also, this line a rather far away from the test that triggers it.

How about:

filename = raw_input("Hello, please enter file name here> ")
if not os.path.isfile(filename):
    if not os.exist(filename):
	print("\nFile {} does not exist")
    else:
	print("\nFile {} is not a regular file")
    sys.exit(1)

print("\nFile {} exists", filename)
# etc.

Or you could skip the whole 'os' thing and use a try/except
construct instead:

#!/usr/bin/env python
#Get the IP Address

import sys, socket

filename = raw_input("Hello, please enter file name here> ")
try:
    infile = open(filename)
except EnvironmentError as e:
    print(e)
    sys.exit(1)

print("\nFile {} exists!".format(filename))
print("\nGetting IP addresses for hosts")
print("\n")
for line in infile:
    hostname = line.strip()
    try:
	ip_address = socket.gethostbyname(hostname)
    except EnvironmentError as e:
	print("Couldn't find IP address for {}: {}".format(hostname, e))
	continue
    print("IP address for {0} is {1}.".format(hostname, ip_address))
else:
    print ("\nFinished the operation")


Using try/except has the advantage that it will correctly
report issues you didn't think about (for example, if file
exists, but you don't have permission to read it).


Hope this helps

-- HansM






More information about the Python-list mailing list