使用dnspython进行DNS解析并对网站进行轮询检查

最近看了天斯大神的《python自动化运维》,里边有DNSPython的案例感觉写的很实用,想拿过来用。但是我在服务器上装了个python3.6。就打算用Python3来替代原来的检查程序。
首先需要导入的是三个模块,dns.resolver,os,httplib2(天斯大神用的是httplib跟httplib2中实用的方法有所不同)
代码如下:

#!/usr/bin/python3
#-*- coding:UTF-8 -*-
import dns.resolver
import os
import httplib2
iplist = []
#appdomain = '.xn--zfr164b'
appdomain = 'xn--zfr54hdx6e.xn--zfr164b'
def get_iplist(domain = ''):
  try: 
    A = dns.resolver.query(domain,'A')
  except Exception as e:
    print("dns resolver error %s" % str(e))
    return
  for i in A.response.answer:
    for j in i.items:
      iplist.append(j.address)
  return True

def checkip(ip):
  #for ip in iplist:
  checkurl =ip+":80" 
  getcontent = ""
  httplib2.socket.setdefaulttimeout(5)
  #conn = httplib2.HTTPConnection(checkurl) #httplib和httplib2的区别
  conn = httplib2.Http()
  try:
    #conn.request("GET","/",header = {"Host":appdomain})
    resp,getcontent = conn.request("http://"+checkurl)
    #print("resp is %s" % resp)
    #getcontent = resp.read(15)
  finally:
    #if getcontent == "<!doctype html>":#httplib2和httplib的区别
    if resp['status'] == '200':
      print("%s is OK!" % ip)
    else:
      print("%s is ERROR!" % ip)
if __name__ == "__main__":
  if get_iplist(appdomain) and len(iplist) >0 :
    for ip in iplist:
      checkip(ip)
  else:
    print("dns resolver error.")

总结一下,看见大神书中的代码,就是感觉大神的思路真是很清晰。每一步都不是无的放矢。特别值得我好好学习。


补充内容:最近要做一个针对IPV6网站可用性进行检查的探测程序。将上边的程序稍作修改就正好合用
1、将query方法中向DNS请求的解析类型从“A”变更为“AAAA”,“A”记录代表的是域名的IPV4解析记录,“AAAA”代表的是域名的IPV6解析记录。国内的话服务器上的nameserver可以配成“114.114.114.114”或者“8.8.8.8”这两个都是支持IPV6地址查询的。
2、在我要探测的网站中有很多域名是经过多重CNAME的。用上边的程序直接执行,在执行到有CNAME记录的域名时会因为缺少address属性而报错。后来也是自己测试了几次,而且也在网上查了查,各种域名记录的rdtype属性是不一致的,其中“A”记录的rdtype属性是1,“CNAME”记录的rdtype是5,“AAAA”记录的rdtype是28.所以在上述程序中增加了一个rdtype的判断。遇到“CNAME”记录就抛弃,终于解决问题。

for i in ipv6_AAAA.response.answer:
        for j in i.items:
            if j.rdtype == 28:
                iplist.append(j.address)
                return iplist
            else:
                pass    

程序上线,正式运行了三天,没啥问题。完美~~~~
最近三大运营商都要开始建设IPV6网络。以后写程序需要注意IPV4和IPV6两种地址的兼容性了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值