0

I have created this below script and it works fine. But the output is not friendly (see below). I want the first line to display only the hostname and IP and remove (,'[], please suggest

('testhostname', [], ['10.10.10.10'])
cannot resolve hostname:  10.10.10.11

import socket
pfile = open ('C:\\Python27\\scripts\\test.txt')
while True:
    IP = pfile.readline()
    if not IP:
        break
    try:
        host = socket.gethostbyaddr(IP.rstrip())
        print host
    except socket.herror, err:
        print "cannot resolve hostname: ", IP
pfile.close()
2
  • @Thomas: gethostbyaddr does a reverse lookup and provides a hostname (along with aliases and alternative IPs), so it's not pointless. See the docs. Commented Sep 26, 2013 at 20:48
  • You're right, I'll delete my stupid comment. Commented Sep 26, 2013 at 20:50

1 Answer 1

4

Rather than printing all of the host tuple that is returned by gethostbyaddr, I suggest unpacking into separate variables that you can then print as you see fit:

hostname, alias_list, ip_addr_list = gethostbyaddr(IP.rstrip())
print hostname, ip_addr_list # or ip_addr_list[0] if you only want the one IP

If you want more control over the formatting, I suggest using the str.format method:

print "hostname: {}, IP(s): {}".format(hostname, ", ".join(ip_addr_list))

Also, a few other code suggestions (not directly related to your main question):

  • Use a with statement rather than manually opening and closing your file.
  • Iterate on the file object directly (with for IP in pfile:), rather than using while True: and calling pfile.readline() each time through.
  • Use the syntax except socek.herror as err rather than the older form with commas (which is deprecated in Python 2 and no longer exists in Python 3).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.