Python script to read through a list and grab reverse DNS entry

208 Views Asked by At

Background: I have always wanted to try my hand at scripting so here goes!

Problem: When gethostbyaddr gets to an IP with no DNS entry it errors and my script doesn't continue on.

Here is what I have so far:

import socket

file = 'ServerList'

f = open(file, 'r')

 lines = f.readlines()
 f.close()
 for i in lines:
    host = i.strip()
    if socket.gethostbyaddr(host) return(True):
        val1 = socket.gethostbyaddr(host)
        print("%s - %s" % (host, val1))
    else:
        print ("%s - No Entry" % (host))

But it errors probably because the return(True) is not proper syntax.

Can anyone help?

Thanks, J

1

There are 1 best solutions below

1
adrianus On

As for basic syntax, you should remove the return(True) as mentioned by itzmeontv.

However, if the method fails it will most likely throw some kind of exception (I tried some servers and got a socket.gaierror), so you'll want to catch and handle those cases with try ... except:

import socket

file = 'ServerList'

f = open(file, 'r')

lines = f.readlines()
f.close()
for i in lines:
    host = i.strip()
    try:
        val1 = socket.gethostbyaddr(host)
        print("%s - %s" % (host, val1))
    except socket.error, exc:
        print ("%s - No Entry, socket error: %s" % (host, exc))

I recommend reading through Handling Exceptions.