一、前言
由于工作中有时要域名解析和获取相关IP归属地信息,所以写了该脚本,方便自己查询使用。
二、脚本内容
#!/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[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)
三、效果
四、相关资料
http://www.dnspython.org/examples.html
http://www.cnblogs.com/CoolRandy/p/3251733.html
时间: 2024-11-07 06:58:38