脚本如何批量查询域名状态

wen 实用脚本 24

本文目录导读:

脚本如何批量查询域名状态

  1. 方法一:使用 Python + whois 库(推荐)
  2. 方法二:使用 dns.resolver 查询DNS状态
  3. 方法三:Shell脚本方式(Linux/Mac)
  4. 方法四:使用 requests 调用第三方API
  5. 使用方法
  6. 注意事项

使用 Python + whois 库(推荐)

import whois
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def check_domain(domain):
    """查询单个域名状态"""
    try:
        w = whois.whois(domain)
        # 判断域名状态
        status = "未注册" if w.status is None else "已注册"
        if status == "已注册":
            # 检查是否过期
            if w.expiration_date:
                exp_date = w.expiration_date[0] if isinstance(w.expiration_date, list) else w.expiration_date
                if exp_date < datetime.now():
                    status = "已过期"
        return {
            'domain': domain,
            'status': status,
            'registrar': w.registrar if w.registrar else 'N/A',
            'expiration_date': w.expiration_date if w.expiration_date else 'N/A'
        }
    except Exception as e:
        return {'domain': domain, 'status': f'查询失败: {str(e)}'}
def batch_check(domains, max_workers=10):
    """批量查询域名"""
    results = []
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(check_domain, domain): domain for domain in domains}
        for future in as_completed(futures):
            results.append(future.result())
    return results
# 使用示例
domains_list = ['example.com', 'google.com', 'test-domain-12345.com']
results = batch_check(domains_list)
# 保存到CSV
with open('domain_status.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=['domain', 'status', 'registrar', 'expiration_date'])
    writer.writeheader()
    writer.writerows(results)
print("查询完成,结果已保存到 domain_status.csv")

使用 dns.resolver 查询DNS状态

import dns.resolver
import csv
def check_domain_dns(domain):
    """通过DNS查询域名状态"""
    status = {}
    status['domain'] = domain
    # 查询A记录
    try:
        answers = dns.resolver.resolve(domain, 'A')
        status['has_a_record'] = True
        status['ip'] = answers[0].to_text()
    except dns.resolver.NXDOMAIN:
        status['has_a_record'] = False
        status['status'] = '未注册/未解析'
    except Exception as e:
        status['has_a_record'] = False
        status['error'] = str(e)
    return status
# 批量查询
domains = ['example.com', 'notexist123456.com']
results = [check_domain_dns(d) for d in domains]

Shell脚本方式(Linux/Mac)

#!/bin/bash
# 批量查询域名状态脚本
# 使用方法: ./check_domains.sh domains.txt
INPUT_FILE="${1:-domains.txt}"
OUTPUT_FILE="domain_status_$(date +%Y%m%d_%H%M%S).csv"
echo "域名,状态,IP地址" > "$OUTPUT_FILE"
while IFS= read -r domain; do
    if [ -z "$domain" ]; then
        continue
    fi
    echo "正在查询: $domain"
    # 使用host命令检查
    if host "$domain" > /dev/null 2>&1; then
        ip=$(host "$domain" | grep "has address" | head -1 | awk '{print $NF}')
        echo "$domain,已解析,$ip" >> "$OUTPUT_FILE"
    else
        # 使用whois辅助判断
        if whois "$domain" 2>/dev/null | grep -q "No match for"; then
            echo "$domain,未注册,N/A" >> "$OUTPUT_FILE"
        else
            echo "$domain,可能已注册但未解析,N/A" >> "$OUTPUT_FILE"
        fi
    fi
    sleep 0.5  # 避免触发限制
done < "$INPUT_FILE"
echo "查询完成!结果保存在 $OUTPUT_FILE"

使用 requests 调用第三方API

import requests
import json
import time
def check_domain_api(domain, api_key=None):
    """使用第三方API查询(示例使用 whoisxmlapi)"""
    url = f"https://www.whoisxmlapi.com/whoisserver/WhoisService"
    params = {
        'domainName': domain,
        'outputFormat': 'JSON',
        'apiKey': api_key or 'Your_API_KEY'
    }
    try:
        response = requests.get(url, params=params)
        data = response.json()
        status = data.get('WhoisRecord', {}).get('registryData', {}).get('domainAvailability', 'UNKNOWN')
        return {
            'domain': domain,
            'status': status,
            'registrar': data.get('WhoisRecord', {}).get('registrarName', 'N/A')
        }
    except Exception as e:
        return {'domain': domain, 'status': f'API查询失败: {str(e)}'}
# 批量处理
def batch_api_check(domains_list, api_key):
    results = []
    for domain in domains_list:
        result = check_domain_api(domain, api_key)
        results.append(result)
        time.sleep(0.2)  # API限速
    return results

使用方法

  1. 准备域名列表 - 创建文本文件,每行一个域名

    example.com
    google.com
    test-domain.com
  2. 安装依赖(Python方法)

    pip install python-whois dnspython requests
  3. 运行脚本

    python domain_checker.py

注意事项

  • 查询限制:WHOIS服务器可能有查询频率限制,建议添加延迟
  • 批量大小:单次不要查询太多,建议分批(每次50-100个)
  • 代理使用:如果需要大量查询,考虑使用代理IP
  • 合法合规:遵守相关法律法规,不要用于恶意目的

推荐使用 Python + whois库 的方法,平衡了易用性和功能完整性。

抱歉,评论功能暂时关闭!