#!/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)