nslookup

Gerson Kurz moc.q-dnan-p at p-nand-q.com
Fri May 17 08:23:24 EDT 2002


On Fri, 17 May 2002 13:55:57 +0100, "ian" <iwaters at btclick.com> wrote:

>hi i posted a message similar to this not long ago
>but the solutions reguired me to import
>third party lib's
>
>can any one post some code to perform an
>nslookup type of reguest
>so i can get a list of mail exchangers for a given
>domain
>
>cheers
>
>

import os, traceback

def MxRecordLookup(hostname):
    "Returns a sorted list of (preference,server) for hostnames' MX
record"
    nslookup_binary = None
    result = []
    if os.name == "nt":
        pipe = os.popen(os.path.join(os.environ["WINDIR"],
"SYSTEM32\\nslookup.exe") + " -query=mx " + hostname)
        for line in pipe.readlines():
            index = line.find("mail exchanger")
            if index >= 0:
                server = line[index+14:].split()[-1]
                preference = 100
                index = line.find("MX preference = ")
                if index >= 0:
                    preference =
int(line[index+16:].split()[0].replace(","," "))
                result.append( (preference, server) )
        pipe.close()
    else:
        pipe = os.popen("/usr/bin/nslookup -silent -query=mx " +
hostname)
        for line in pipe.readlines():
            index = line.find("mail exchanger")
            if index >= 0:
                tokens = line[index+16:].split()
                if len(tokens) == 2:
                    tokens[0] = int(tokens[0])
                    result.append( tuple(tokens) )
        pipe.close()
    result.sort()
    return result





More information about the Python-list mailing list