Python automated operation and maintenance: DNS round robin domain name service monitoring (IP address and DNS processing module IPy processing module dnspython)

IP address planning is a very important aspect of network design, planning will directly affect the efficiency of routing algorithms, including aspects of network performance, scalability and so on. In the process, we will inevitably have to calculate a lot of IP address, including the network segment, network mask, broadcast address, subnet numbers, Ip types.
IPy module can be a good aid to complete the planning Ip our colleges and universities.

1.1 IP address, subnet basic processing

IPy IP module contains class, which can be easily processed, and the majority of the format of IPv6 network and the IPv4 address.
Such methods can be distinguished by the version IPv4 and the IPv6
EG:

>>> from IPy import IP
>>> IP('192.168.217.135').version()
4
>>> IP('::1').version()            
6
>>> 

Output IP number and a list of all IP addresses on the network segment specified by the segment,

[root@devops python]# vim ip.py    
  1 #!/usr/bin/env python
  2 from IPy import IP
  3 ip = IP('192.168.217.135')
  4 print (ip.len())
  5 for x in ip:
  6     print(x)

执行结果如下:

[root@devops python]# python ip.py 
1
192.168.217.135


Here are a few common methods used Ip class, including reverse lookup name, IP type, IP conversion

>>> ip = IP('192.168.217.135')
>>> ip.reverseNames()    #反向解析地址格式
['135.217.168.192.in-addr.arpa.']

>>> ip.iptype()     # 为私网类型
'PRIVATE'
>>> 
>>> IP('8.8.8.8').int()    #转换为整形格式
134744072
>>> IP('8.8.8.8').strHex()     #转换为十六进制格式
'0x8080808'
>>> IP('8.8.8.8').strBin() #转换为二进制格式
'00001000000010000000100000001000'
>>> 

Example: return network, mask, or subnet broadcast Ip according to the input, reverse analysis, the subnet number, type and other information Ip

[root@devops python]# vim pyIPy.py 
  1 #!/usr/bin/env python
  2 from IPy import IP
  3 
  4 #def input(param):
  5 #    pass
  6 ip_s = input('Please input an IP or net-range:')
  7 #if ip_s is None:
  8 #    print("ip_s is None!!!")
  9 ips = IP(ip_s)
 10 if len(ips) > 1:
 11     print('net: %s' % ips.net())
 12     print('netmask: %s' % ips.netmask())
 13     print('broadcast: %s' % ips.broadcast())
 14     print('reverse address: %s' % ips.reverseNames()[0])
 15     print('subnet: %s' % len(ips))
 16 else:
 17     print('reverse address: %s' % ips.reverseName()[0])
 18 
 19 print('hexadecimal: %s' % ips.strHex())
 20 print('binary ip: %s' % ips.strBin())
 21 print('iptype: %s' % ips.iptype())
 22 print('ip_version: %s' % ips.version())

运行输出结果:

[root@devops python]# python pyIPy.py 
Please input an IP or net-range:192.168.100.10
reverse address: 1
hexadecimal: 0xc0a8640a
binary ip: 11000000101010000110010000001010
iptype: PRIVATE
ip_version: 4


[root@devops python]# python pyIPy.py 
Please input an IP or net-range:192.168.100.0/24
net: 192.168.100.0
netmask: 255.255.255.0
broadcast: 192.168.100.255
reverse address: 100.168.192.in-addr.arpa.
subnet: 256
hexadecimal: 0xc0a86400
binary ip: 11000000101010000110010000000000
iptype: PRIVATE
ip_version: 4
[root@devops python]# 
2 . DNS processing module dnspython

dnspython ( http://www.dnspyhon.org ) is a DNS toolkit implemented in Python, it supports almost all record types,
can be used to query, update ZONE transmission and dynamic information,
while supporting TSIG (Transaction Signature) validation message and EDNSO (extended DNS).
In the system management, we can use its search function to implement DNS service monitoring and verification of the analytical results, you can replace nslookup and dig and other tools to easily achieve integration with existing platforms.

首先介绍dnspython模块的安装,这里采用源码的安装方式如下:
# http://www.dnspython.org/kits/1.9.4/dnspython-1.9.4.tar.gz
# tar -zxvf dnspython-1.9.4.tar.gz 
# cd dnspython-1.9.4
# python setup.py install



dnspython模块提供了大量的DNS处理方法,最常用的方法是域名查询
dnspython供了一个DNS解析器类一resolver, 使用它的query方法来实现域名的查询功能。

query()方法的定义如下:


query(self ,qname,rdtype=1,rdclass=1,tcp=Flase,source=None,raise_on_no_answer=True,source_port=0)

其中,qname参数为查询的域名。rdtype参数用来指定RR资源的类型,常用的有以下几种:

A记录,将主机名转换为Ip地址
MX记录,邮件交换记录,定义邮件服务器的域名
CNAME记录 指别名记录,实现域名间的映射
NS记录,标记区域的域名服务器以及授权子域
PTR记录 反向解析,与A记录相反,将Ip转换为主机名
SOA记录 SOA标记,一个起始授权区的定义

2.1 A record:
[root@devops python]# vim dnsDemo.py 

  1 #!/usr/bin/env python
  2 import dns.resolver
  3 #def raw_input(param):
  4 #   pass
  5 domain = input('Please input an domain:')
  6 A = dns.resolver.query(domain,rdtype='A')    #指定查询类型为A记录
  7 for i in A.response.answer:   #通过response.answer 方法获取查询回应信息
  8     for j in i.items:   #遍历回应信息
  9         print (j)


运行结果:
[root@devops python]# python dnsDemo.py 
Please input an domain:www.google.com
6.6.6.6
[root@devops python]# 
2.2 MX records:
[root@devops python]# vim simple1MX.py 
  1 #!/usr/bin/env python
  2 import dns.resolver
  3 domain = input('Please input an domain:')  # example 163.com
  4 MX = dns.resolver.query(domain,rdtype='MX')   #指定查询类型为MX记录
  5 for i in MX:	 #遍历回应信息
  6     print ('MX preference = ',i.preference,'mail exchanger = ',i.exchange)

运行结果:

[root@devops python]# python simple1MX.py 
Please input an domain:baidu.com
MX preference =  10 mail exchanger =  mx.maillb.baidu.com.
MX preference =  20 mail exchanger =  jpmx.baidu.com.
MX preference =  15 mail exchanger =  mx.n.shifen.com.
MX preference =  20 mail exchanger =  mx50.baidu.com.
MX preference =  20 mail exchanger =  mx1.baidu.com.
[root@devops python]# 
[root@devops python]# python simple1MX.py
Please input an domain:163.com
MX preference =  10 mail exchanger =  163mx02.mxmail.netease.com.
MX preference =  10 mail exchanger =  163mx03.mxmail.netease.com.
MX preference =  50 mail exchanger =  163mx00.mxmail.netease.com.
MX preference =  10 mail exchanger =  163mx01.mxmail.netease.com.

2.3 NS record:
[root@devops python]# vim simple1NS.py 
  1 #!/usr/bin/env python
  2 import dns.resolver
  3 #LimitOneLeavelDomain example baidu.com
  4 domain = input('Please input an domain:')
  5 ns = dns.resolver.query(domain,rdtype='NS')
  6 for i in ns.response.answer:
  7     for j in i.items:
  8         print (j.to_text())
~        

运行结果:
注意:这里仅仅只能输入一级域名,如baidu.com

[root@devops python]# python simple1NS.py    
Please input an domain:baidu.com
ns7.baidu.com.
ns4.baidu.com.
dns.baidu.com.
ns3.baidu.com.
ns2.baidu.com.
                         
2.4 CNAME record:
[root@devops python]# vim simple2CNAME.py 
  1 #!/usr/bin/env python
  2 import dns.resolver
  3 domain = input('Please input an domain:')
  4 cname = dns.resolver.query(domain,rdtype='CNAME')   #指定查询类型为CNAME记录
  5 for i in cname.response.answer:    #结果将回应cname后的目标域名
  6     for j in i.items:
  7         print (j.to_text())

Comprehensive: DNS round robin domain name service monitoring

Most DNS resolution is a domain name corresponds to an IP address, but can be done through DNS round robin technique a domain name corresponding to multiple IP,
in order to achieve the most simple and efficient load balancing, but the biggest drawbacks of this scenario is not the target host can not be automatically removed when used, so do the monitoring is critical eye works available services host.
This example by analyzing resolve the IP of the current domain, combined with service port detection to automatically monitor, add in DNS, the IP is deleted,
without the need for changes to the monitoring scripts. FIG architecture using PPT as follows :( drawing, the effect is less evident)
Here Insert Picture Description
Here Insert Picture Description

1. Step
1) to achieve resolve name of the town, get all of the domain name A records resolve IP list;
2) the list of IP HTTP level of detection.

2. code analysis
first step acquired by dns.resolver.query () method ^ business city name record information, check out all the list of IP addresses, then use httplib module request () method in a manner GET request monitoring page monitoring service for all IP services if normal service.


[root@devops python]# vim simple5DnsDomain.py 
  1 #!/usr/bin/python
  2 #-*- coding:utf-8 -*-
  3 import dns.resolver
  4 import os
  5 import httplib
  6 
  7 iplist=[]   #定义域名IP的列表变量
  8 appdomain='www.google.com.hk'   #定义业务域名
  9 
 10 def get_iplist(domain=""):  #域名解析函数,解析成功IP将被追加到iplist
 11     try:
 12         A = dns.resolver.query(domain,rdtype='A')   #解析A记录类型
 13     except Exception,e:
 14         print "dns resolver error:"+str(e)
 15         return
 16     for i in A.response.answer:
 17         for j in i.items:
 18             iplist.append(j.address)    #追加到iplist
 19     return True
 20 def checkip(ip):
 21     checkurl=ip+":80"
 22     getcontent=""
 23     httplib.socket.setdefaulttimeout(5)     #定义http连接超时时间为5秒
 24     conn=httplib.HTTPConnection(checkurl)   #创建http连接对象
 25 
 26     try:
 27         conn.request("GET","/",headers = {"Host":appdomain})    #发起URL请求,添加host主机头
 28         r=conn.getresponse()
 29         getcontent=r.read(15)   #获取URL页面前15个字符,以便做可用性校验
 30     finally:
 31         if getcontent=="<!doctype html>":   #监控URL页的内容一般是事先定义好的,比"HTTP200"等
 32             print ip+" [OK]"
 33         else:
 34             print ip+" [Error]"     #此处可放告警程序,可以是邮件、短信通知
 35 if __name__=="__main__":
 36     if get_iplist(appdomain) and len(iplist)>0:     #条件:域名解析正确且至少返回一个IP
"simple5DnsDomain.py" 40L, 1326C                                                                

We can put this script in crontab regular operation, combined with alarm program, so a complete round robin-based domain name service monitoring.

Guess you like

Origin blog.csdn.net/qq_28513801/article/details/95228583