Python -- an example of business monitoring based on domain name polling

Posted by charlesg on Thu, 30 Apr 2020 20:59:38 +0200

Please indicate the source of Reprint:

Most of DNS resolution is a domain name corresponding to an IP address, but through DNS polling technology, a domain name corresponding to multiple IPS can be achieved, so as to achieve the simplest and most efficient load balancing. However, the biggest drawback of this scheme is that the target host cannot be automatically removed when it is not available, so it is very important to monitor the service availability of the business host. This example realizes automatic monitoring by analyzing the resolution IP of current domain name and combining with service port detection. When adding or deleting IP in domain name resolution, there is no need to modify the monitoring monitor.
We are mainly divided into the following two steps to realize this example:

1) Realize domain name resolution, obtain all records of domain name resolution IP list
2) HTTP level detection of IP list

The specific code is as follows:

# -*- coding:UTF-8 -*-
Created on 2018 January 3, 2010

@author: liuyazhuang
import dns.resolver
import httplib

#Define domain name IP list variable
iplist = []
#Define business domain name
appdomain = "Your domain name"

#Domain name resolution function. The resolved IP address will be appended to the iplist
def get_iplist(domain = ""):
        A = dns.resolver.query(domain, 'A')
    except Exception, e:
        print "dns resolver error: " + str(e)
    for i in A.response.answer:
        for j in i.items:
            #Append IP to list
    return True

#Check whether IP can connect
def checkip(ip):
    checkurl = ip+":80"
    getcontent = ""
    #Define http connection timeout 5 seconds
    #Create http connection object
    conn = httplib.HTTPConnection(checkurl)
        #Initiate URL request and add host host header
        conn.request("GET", "/", headers = {"Host" : appdomain})
        r = conn.getresponse()
        getcontent =
        #The content of monitoring URL page is generally defined in advance, such as "HTTP 200", etc
        print getcontent
        if getcontent == "<!DOCTYPE html>":
            print ip + " [OK]"
            #Alarm program can be put here, which can be email or SMS notification
            print ip + " [ERROR]"
if __name__ == "__main__":   
    #Condition: domain name resolves correctly and returns at least one IP
    if get_iplist(appdomain) and len(iplist) > 0:
        for ip in iplist:
        print "dns resolver error."
We can put this Python script into the crontab execution plan, and combine with the alarm program, which can basically meet the business monitoring based on domain name polling.

Topics: DNS socket Python crontab