Search code examples
pythonpython-2.7ip-addressnslookup

Using nslookup to find domain name and only the domain name


Currently I have a text file with mutiple IP's I am currently attempting to pull only the domain name from the set of information given using nslookup (code below)

with open('test.txt','r') as f:
    for line in f:
        print os.system('nslookup' + " " + line)

This works in so far that it pulls all the information from the first IP's. I can't get it passed the first IP but I'm currently attempting to clean up the information recived to only the Domain name of the IP. Is there any way to do that or do I need to use a diffrent module


Solution

  • Like IgorN, I wouldn't make a system call to use nslookup; I would also use socket. However, the answer shared by IgorN provides the hostname. The requestor asked for the domain name. See below:

    import socket
    with open('test.txt', 'r') as f:
        for ip in f:
            fqdn = socket.gethostbyaddr(ip)  # Generates a tuple in the form of: ('server.example.com', [], ['127.0.0.1'])
            domain = '.'.join(fqdn[0].split('.')[1:])
            print(domain)
    

    Assuming that test.txt contains the following line, which resolves to a FQDN of server.example.com:

    127.0.0.1
    

    this will generate the following output:

    example.com
    

    which is what (I believe) the OP desires.