utydgf 发表于 2016-7-20 10:49:17

利用python脚本实现域名解析和归属地信息查询

一、前言
由于工作中有时要域名解析和获取相关IP归属地信息,所以写了该脚本,方便自己查询使用。

二、脚本内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
#coding:utf-8

import dns.resolver
import urllib
import chardet
import sys
import re

ip_list = []
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
    print '%-*s--->%*s' % (18,ip,20,belong)


if __name__ == '__main__':
    get_iplist(query_domain)
    for ip in ip_list:
      get_ipbelong(ip)





三、效果



页: [1]
查看完整版本: 利用python脚本实现域名解析和归属地信息查询