5

Objective is to read a list of domains from a file and perform lookup to confirm reachability and resolution from my end.

This is what I have written:

#!/usr/bin/python

import os
import socket

f = open('file1.lst', 'r')
s = f.readlines()

for i in s:
    print i
    socket.gethostbyname(i.strip())

f.close()

socket.gethostbyname() line throws an exception.

xskxzr
  • 12,442
  • 12
  • 37
  • 77
Sunshine
  • 479
  • 10
  • 24
  • @Simon adding i.strip() makes this work. But as soon as it encounters an inexistent domain or one that couldn't be resolved, it throws an exception & breaks out. – Sunshine Sep 12 '11 at 12:36

4 Answers4

4
for i in s:
    print i
    try:
        socket.gethostbyname(i.strip())
    except socket.gaierror:
        print "unable to get address for", i

If an address could not be found, then gethostbyname will raise an exception (not throw). This is the way error handling is done in Python. If you know how to properly deal with the error, the you should catch it with an except clause.

Note that you will need some more code to also check for connectivity.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • +1. One question though, while reading up on exceptions, I saw we can also use else clause. What'd be the diff b/w else & except? – Sunshine Sep 12 '11 at 13:52
  • 1
    See [this question](http://stackoverflow.com/questions/855759/python-try-else) for a good answer. – Ethan Furman Sep 12 '11 at 16:11
2

This is what I wrote to do the same thing. It may be of use to you:

import argparse
from socket import getaddrinfo

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Check for validity of domains in list exported from exchange', version='%(prog)s 1.0')
    parser.add_argument('infile', nargs='+', type=str, help='list of input files')
    args = parser.parse_args()

    # Read domains from file
    domains = []
    for f in args.infile:
        with open(f, 'rt') as data:
            for line in data.readlines():
                split = line.replace('\x00',"").split(':')
                if split[0].strip() == 'Domain':
                    domains.append(split[1].strip())

    # Check each domain
    for domain in domains:
        try:
            getaddrinfo(domain, None)
        except Exception, e:
            print "Unable to resolve:", domain

Note that my input file has a slightly different format than yours, so you will need to adjust the input section.

Stan James
  • 2,535
  • 1
  • 28
  • 35
Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
  • 1
    Catching `Exception` is not usually a good idea as it is almost every possible exception in the system, and can hide other problems. You probably want to catch either `socket.gaierror` or `socket.error`. – Ethan Furman Sep 12 '11 at 13:33
  • Thanks @Spencer. The exception handling block was quite useful. On a separate note, I guess you could've used gethostbyname() in your script too. – Sunshine Sep 12 '11 at 13:48
  • @Ethan, I was using 'Exception' initially, but after reading your comments, I looked into other exception keywords as well. My script gives a gaierror, so I included this instead of 'exception', eventually. Thanks – Sunshine Sep 12 '11 at 13:51
  • @Ethan Furman At the time I wrote this, I just needed a quick short script to check for legitimacy of domains. I only cared about domains it had a problem resolving, and I wasn't particular about why. However, I do agree that a more thorough script should only catch specific exceptions. – Spencer Rathbun Sep 12 '11 at 14:08
1

You are passing the string 'i' to gethostbyname() rather than the variable i.

It should be socket.gethostbyname(i)

This question may be of use: Checking if a website is up via Python

Community
  • 1
  • 1
Acorn
  • 49,061
  • 27
  • 133
  • 172
1

The gethostbyname line should be

socket.gethostbyname(i.strip())

with no quotes around the i variable. The strip() is to remove trailing lf \ cr characters which will cause an error.

Note: This will only verify that the domain exists in the DNS system, not that it is reachable / running. For that you will have to actuallyopen a connection to the remote host, on a port it is listening on,

Simon Callan
  • 3,020
  • 1
  • 23
  • 34
  • adding i.strip() makes this work. But as soon as it encounters an inexistent domain or one that couldn't be resolved, it throws an exception & breaks out. – Sunshine Sep 12 '11 at 12:39
  • You need to handle the exception. This page explains try..except http://en.wikibooks.org/wiki/Python_Programming/Exceptions – Acorn Sep 12 '11 at 12:49