2013년 12월 17일 화요일

[Pyhon] MX 호스트 찾기

import os,sys,popen2,re

resolver = "/usr/bin/nslookup -query=mx "             # for Linux
#resolver = "/usr/sbin/nslookup -query=mx "          # for Solairs
#C:\WINDOWS\SYSTEM32\NSLOOKUP -query=mx "  # for M$

def queryMX(host):
    mx = []
    addr = {}

    fout,fin = popen2.popen2(resolver + host)

    line = fout.readline()
    while line <> '':
        m = re.search(
            'preference\s*=\s*(\d+),\s*mail\sexchanger\s*=\s*([\w\.]+)',
            line)
        if m:
            mx.append((eval(m.group(1)),m.group(2)))
        else:
            m = re.search(
                '([\w\.]+)\s*internet\saddress\s*=\s*([\d\.]+)',
                line)
            if m: addr[m.group(1)] = m.group(2)

        line = fout.readline()

    if mx == []: return mx

    mx.sort()
    result = []
    for i,k in mx:
        try:
            result.append((k,addr[k]))
        except:
            pass

    return result

댓글 없음:

댓글 쓰기