Doing a whois with a list of domain names

Andy K picture Andy K · Nov 6, 2014 · Viewed 11.9k times · Source

I've got a file of domain names e.g. equivalent to 2500.

I would like to do a whois on these domain names.

Issue is I've never done that and don't know where to start. If you have any ideas, I'm all ears.

TIA.

Answer

Alu picture Alu · Nov 16, 2014

You can also use the Linux commandtool whois. The following code opens a subprocess and searches for the domain.

But you have to be carefull with many requests in short time. The servers will eventually block you after a while. ;)

import subprocess

def find_whois(domain):
    # Linux 'whois' command wrapper
    # 
    # Executes a whois lookup with the linux command whois.
    # Returncodes from: https://github.com/rfc1036/whois/blob/master/whois.c

    domain = domain.lower().strip()
    d = domain.split('.')
    if d[0] == 'www': d = d[1:]

    # Run command with timeout
    proc = subprocess.Popen(['whois', domain], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    ans,err = proc.communicate(input)

    if err == 1: raise WhoisError('No Whois Server for this TLD or wrong query syntax') 
    elif err == 2: raise WhoisError('Whois has timed out after ' + str(whois_timeout) + ' seconds. (try again later or try higher timeout)')
    ans = ans.decode('UTF-8')
    return ans


with open('domains.txt') as input:
    with open('out.txt','a') as output:
        for line in input:
            output.write(find_whois(line))

The with open as statement handles the filestream. The 'a' at the output file means the file is opened in append-mode.