查看dns模块是否安装
#pip list|grep dnspython
开源模块dnspython安装
#pip install dnspython
(resolver是dns解析类)
query方法域名查询的帮助信息
参数:
qname:查询的域名
rdtype:指定解析记录
-A 地址记录,返回域名解析的ip地址
-NS 域名服务器记录,返回下一级域名的服务器地址(只能是域名)
-MX 邮件记录,返回接收电子邮件的服务器地址
-CNAME 别名记录,实现域名之间的映射
-PTR 反向解析,与A记录相反,将ip地址转换成域名
rdclass:网络类型
tcp:是否使用tcp协议
source:查询源的地址
raise_on_no_answer:指定查询无应答的异常触发,默认为True
source_port:查询源的端口
import dns.resolver
domain = input('Please input an domain: ')
A = dns.resolver.query(domain, 'A') #指定查询类型 A 表示主机记录
#获取域名的A记录
1、dig方法获取
2、python程序获取
#直接获取A记录的ip地址
for i in A.response.answer: #遍历相应的信息
for j in i.items:
print(j.to_text())
MX = dns.resolver.query(domain, 'MX') #指定为邮件交换记录 139.com/163.com
for i in MX:
print(i)
#print('MX preference =', i.preference('优先级'), 'mail exchanger =', i.exchange('FQDN名,完整的合格域名'))
ns = dns.resolver.query(domain,'NS') #标记域名服务器 google.com一级域名
for i in ns.response.answer:
for j in i.items:
#print(j.to_text())
print(j)
cname = dns.resolver.query(domain, 'CNAME') #别名
for i in cname.response.answer:
for j in i.items:
print(j)
===============================================
python2中http请求使用httplib库
python2中http请求使用http.client库
dns轮循例子
import dns.resolver
import os
import http.client
iplist=[] #定义域名IP列表变量
appdomain="www.baidu.com" #定义业务域名
def get_iplist(domain=""): #域名解析函数,解析成功IP将追加到iplist
try:
A = dns.resolver.query(domain, 'A') #解析A记录类型
except Exception as e:
print("dns resolver error:"+str(e))
return
for i in A.response.answer:
for j in i.items:
if not j.to_text().startswith('www') or not j.to_text().endswith('com.'):
iplist.append(j.to_text()) #追加到iplist
return True
def checkip(ip):
checkurl=ip+":80"
getcontent=""
http.client.socket.setdefaulttimeout(5) #定义http连接超时时间(5秒)
conn = http.client.HTTPConnection(checkurl) #创建http连接对象
try:
conn.request("GET", "/",headers = {"Host": appdomain}) #发起URL请求,添加host主机头
r=conn.getresponse()
getcontent =r.read(15) #获取URL页面前15个字符,以便做可用性校验,注意结果是字节
finally:
if getcontent==b"<!DOCTYPE html>": #监控URL页的内容一般是事先定义好,比如“HTTP200”等
print(ip+" [OK]")
else:
print(ip+" [Error]") #此处可放告警程序,可以是邮件、短信通知
if name=="main":
if get_iplist(appdomain) and len(iplist)>0: #条件:域名解析正确且至少要返回一个IP
for ip in iplist:
checkip(ip)
else:
print("dns resolver error.")
1万+

被折叠的 条评论
为什么被折叠?



