Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script to validate domains

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.

like image 264
Sunshine Avatar asked Sep 12 '11 12:09

Sunshine


People also ask

How do you validate a domain?

The WHOIS database is an online directory that will provide information on the registrar of domain names. When you purchase a domain name, the issuing company will send your personal details to the WHOIS database. If you want to find out if a domain name is validated, simply type the URL into the WHOIS database.

How do I find the regex for a domain name?

[A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long.


3 Answers

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.

like image 87
Ethan Furman Avatar answered Oct 02 '22 23:10

Ethan Furman


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.

like image 22
Spencer Rathbun Avatar answered Oct 03 '22 00:10

Spencer Rathbun


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

like image 27
Acorn Avatar answered Oct 02 '22 23:10

Acorn