背景
公司需要做一个校验客户域名是否为咱们自己子域名的工具,如果不是则打印日志出来就好了,这里通过CNAME来做校验。
代码实现
#!/usr/bin/python
# -*- coding: utf-8 -*-
import dns.resolver
import requests
import json
import logging
base_domains = 'ap-southeast-1.test.com.'
base_url = 'http://127.0.0.1:8087/domain?pageSize=10&pageNo='
page = 1
size = 20
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger("check_domain")
# cname解析检测模块
def check_domain(domain):
resolver = dns.resolver.Resolver()
resolver.lifetime = resolver.timeout = 5.0
try:
cname = resolver.resolve(domain, 'CNAME')
logger.info('-----------------------CNAME记录-----------------------')
for i in cname.response.answer:
for j in i.items:
if not base_domains == j.to_text():
logger.info('【' + domain + '】不是子域名')
except dns.resolver.LifetimeTimeout:
logger.info("timed out, try again now")
check_domain(domain)
# 用户域名列表请求模块
def process(url, page_no):
try:
res = requests.get(url + page_no.__str__())
logger.info("response result:" + res.text)
data = json.loads(res.text)
if data['success']:
for domain in data['resultObject']:
check_domain(domain)
total_count = data['totalCount']
next_page = page_no + 1
if next_page * size <= total_count:
process(url + next_page.__str__(), next_page)
else:
logger.info("request fail, place try again later")
return
except requests.exceptions.ConnectionError:
logger.info("network error, place try again later")
if __name__ == '__main__':
process(base_url, page)