Python Forum

Full Version: A small/simple class for running nslookup on a list of domain names
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
might make it return more stuff in the future... here it is for now:

#! /usr/bin/python3
from subprocess import Popen, PIPE
from re import findall


class NSLookup:
    def __init__(self, domains):
        self.domains = domains
        self.canonical = r"\s+canonical\s+name\s+=\s+(.*)\s+"
        self.address = r"Address:\s+(\d+.\d+.\d+.\d+)\s+"

    def examine(self):
        for d in self.domains:
            data = {'domain': d, 'names': [], 'ips': []}
            cmd = ["nslookup",  d]
            out = Popen(cmd, stdout=PIPE).communicate()[0].decode()
            server_names = findall(self.canonical, out)
            server_ips = findall(self.address, out)
            for name in server_names:
                data['names'].append(name)
            for ip in server_ips:
                data['ips'].append(ip)
            yield data


if __name__ == "__main__":
    # EXAMPLE CLIENT:
    domain_list = [
        'www.unc.edu', 'www.umb.edu', 'www.harvard.edu',
        'www.cornell.edu', 'www.psu.edu', 'www.cam.ac.uk',
        'www.umass.edu', 'www.mit.edu', 'www.unimelb.edu.au'
    ]
    for test in NSLookup(domain_list).examine():
        print(test)
EDIT:

Replaced those two for loops with list comprehensions:

#! /usr/bin/python3
from subprocess import Popen, PIPE
from re import findall


class NSLookup:
    def __init__(self, domains):
        self.domains = domains
        self.canonical = r"\s+canonical\s+name\s+=\s+(.*)\s+"
        self.address = r"Address:\s+(\d+.\d+.\d+.\d+)\s+"

    def examine(self):
        for d in self.domains:
            data = {'domain': d, 'names': [], 'ips': []}
            cmd = ["nslookup",  d]
            out = Popen(cmd, stdout=PIPE).communicate()[0].decode()
            server_names = findall(self.canonical, out)
            server_ips = findall(self.address, out)
            data['names'] = [name for name in server_names]
            data['ips'] = [ip for ip in server_ips]
            yield data


if __name__ == "__main__":
    # EXAMPLE CLIENT:
    domain_list = [
        'www.unc.edu', 'www.umb.edu', 'www.harvard.edu',
        'www.cornell.edu', 'www.psu.edu', 'www.cam.ac.uk',
        'www.umass.edu', 'www.mit.edu', 'www.unimelb.edu.au'
    ]
    for test in NSLookup(domain_list).examine():
        print(test)