python3 批量查询域名A记录 & CNAME

场景:需要批量查询域名信息

需要生成一个 domain_in.txt的文件
文件内容格式(尾行不可有空行):

baidu.com
bilibili.com

代码

import random
import string
from dns.resolver import Resolver
import requests
import socket
from parsel import Selector

"""
# python3
pip install dnspython3
pip install lxml
pip install requests
pip install parsel
"""

dns_resolver = Resolver()
dns_resolver.nameservers = ["8.8.8.8", "8.8.4.4"]


def get_ip_from_domain(domain):
    domain = domain.lower().strip()
    try:
        return dns_resolver.query(domain, 'CNAME')[0].to_text()
    except Exception:
        return str(None)


def open_domainlist(filename):
    with open(filename, encoding="utf-8") as f:
        return f.readlines()


def get_whoisname(domainwhois):
    requests_data = {
        "domain": str(domainwhois),
        "type": 'true',
        "standard": 'true'
    }
    url = 'https://api.devopsclub.cn/api/whoisquery'
    get_whoisnames = requests.get(url=url, params=requests_data).json()
    return get_whoisnames


def for_domainlist(domainnamess):
    for domain_one in domainnamess:
        # 组合
        domain_one_n = domain_one.strip('\n')
        www_domain = 'www' + '.' + domain_one_n
        # 打印
        print(domain_one_n + ' 域名解析检查: ')
        whois_xpath(domain_one_n)
        get_domain_ip(domain_one_n)
        get_domain_or_ip('www', domain_one_n)
        print(www_domain + ' CNAME = ' + get_ip_from_domain(www_domain))
        print('-' * 30)


def whois_xpath(whois_name):
    # 获取返回响应的html文件
    url = 'https://who.is/whois/' + whois_name

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.61'
    }
    selector = Selector(text=requests.post(url=url, headers=headers, timeout=600).text)
    select_url = selector.xpath('/html/body/div[3]/div[2]/div[5]/div[1]/div[3]/div/div[3]/div[2]/text()').extract_first()
    print(select_url)


def get_domain_ip(domain):
    try:
        myaddr = socket.getaddrinfo(domain, 'http')
        print('顶级域名解析值: ' + domain + ' = ' + myaddr[0][4][0])
    except Exception:
        print('顶级域名解析不存在')


def get_domain_or_ip(a, domain):
    try:
        domain_sub = a + '.' + domain
        myaddr = socket.getaddrinfo(domain_sub, 'http')
        print(domain_sub + ' = ' + myaddr[0][4][0])
    except Exception:
        print('解析' + a + '不存在')


if __name__ == '__main__':
    # input('确认相对路径存在 domain_in.txt /  <Enter>')
    DomainNames = open_domainlist('domain_in.txt')
    for_domainlist(DomainNames)
    # input('Press <Enter>')

posted @ 2020-08-28 12:25  运维之爪  阅读(1196)  评论(0编辑  收藏  举报