python實現域名解析和歸屬地查詢

  1. 前言
    工做中有時要查詢域名解析和獲取域名相關IP歸屬地信息
  2. 安裝依賴
    python2:
    pip install dnspython
    python3:
    python3 -m pip install -i https://pypi.douban.com/simple/ dnspython3
  3. 腳本內容
    #!/usr/bin/env python
    #coding:utf-8
     
    import dns.resolver
    import urllib
    import chardet
    import sys
    import re
     
    ip_list = []
    query_domain = sys.argv[1]
    #query_domain = raw_input('Please input a domain: ')
     
    # 先查詢是否有CNAME,若是有則經過CNAME獲取到A記錄;若是沒有直接獲取A記錄,而後返回到一個列表中
    def get_iplist(domain):
        try:
            cn = dns.resolver.query(domain,'CNAME')
            for i in cn.response.answer:
                for j in i.items:
                    cname_domain = j.to_text() 
            print '========================================'
            print '    CNAME  --->', cname_domain
            print '========================================'
        except:
            pass
        else:
            A = dns.resolver.query(cname_domain,'A')
            for i in A.response.answer:
                for j in i.items:
                    try:
                        ip_list.append(j.address)
                    except:
                        get_iplist(str(j))
             
        try:
            A = dns.resolver.query(domain,'A')
            for i in A.response.answer:
                for j in i.items:
                    ip_list.append(j.address)
        except:
            pass
        return ip_list
     
    # 經過調用ip138.com來獲取IP歸屬地信息
    def get_ipbelong(domain_ip):
        url = 'http://ip138.com/ips138.asp?ip=%s&action=2' % domain_ip
        content = urllib.urlopen(url).read()
        typeEncode = sys.getfilesystemencoding()
        infoencode = chardet.detect(content).get('encoding','utf-8')
        html = content.decode(infoencode,'ignore').encode(typeEncode)
        ip = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',html)
        result = re.findall(r'(<li>.*?</li>)',html)
        belong = result[0][14:-5]
        print '%-*s--->%*s' % (18,ip[0],20,belong)
     
     
    if __name__ == '__main__':
        get_iplist(query_domain)
        for ip in ip_list:
            get_ipbelong(ip)
  4. 使用python domain2ip.py www.baidu.com
相關文章
相關標籤/搜索