本文目录导读:

我来为你提供几个不同场景下的DNS解析速度监控脚本。
基础Python脚本 - 监控单个域名
#!/usr/bin/env python3
"""
DNS解析速度监控脚本
功能:测试指定域名的DNS解析时间
"""
import socket
import time
import argparse
from datetime import datetime
def resolve_dns(domain, dns_server=None, timeout=5):
"""测试DNS解析速度"""
try:
start_time = time.time()
if dns_server:
# 使用指定DNS服务器
import dns.resolver
resolver = dns.resolver.Resolver()
resolver.nameservers = [dns_server]
resolver.timeout = timeout
resolver.lifetime = timeout
answers = resolver.resolve(domain, 'A')
ip = str(answers[0])
else:
# 使用系统默认DNS
ip = socket.gethostbyname(domain)
resolve_time = (time.time() - start_time) * 1000 # 转换为毫秒
return resolve_time, ip
except Exception as e:
return None, str(e)
def main():
parser = argparse.ArgumentParser(description='DNS解析速度监控')
parser.add_argument('domain', help='要监控的域名')
parser.add_argument('--dns', help='指定DNS服务器(可选)')
parser.add_argument('--count', type=int, default=1, help='测试次数')
parser.add_argument('--interval', type=int, default=0, help='测试间隔(秒)')
args = parser.parse_args()
print(f"DNS解析速度监控 - 域名: {args.domain}")
print(f"时间戳: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("-" * 50)
for i in range(args.count):
if i > 0 and args.interval > 0:
time.sleep(args.interval)
resolve_time, ip = resolve_dns(args.domain, args.dns)
if resolve_time is not None:
print(f"#{i+1:3d} | 解析时间: {resolve_time:6.2f}ms | IP: {ip}")
else:
print(f"#{i+1:3d} | 解析失败: {ip}")
if __name__ == "__main__":
# 安装依赖:pip install dnspython
main()
高级监控脚本 - 多DNS服务器对比
#!/usr/bin/env python3
"""
高级DNS监控脚本 - 多DNS服务器对比测试
"""
import dns.resolver
import time
import statistics
import json
from datetime import datetime
import argparse
class DNSMonitor:
def __init__(self, domains, dns_servers=None, timeout=5):
self.domains = domains
self.dns_servers = dns_servers or [
'8.8.8.8', # Google
'1.1.1.1', # Cloudflare
'114.114.114.114', # 国内114
'223.5.5.5', # 阿里
]
self.timeout = timeout
self.results = {}
def resolve_with_dns(self, domain, dns_server):
"""使用指定DNS服务器解析"""
resolver = dns.resolver.Resolver()
resolver.nameservers = [dns_server]
resolver.timeout = self.timeout
resolver.lifetime = self.timeout
start_time = time.time()
try:
answers = resolver.resolve(domain, 'A')
resolve_time = (time.time() - start_time) * 1000
ips = [str(r) for r in answers]
return resolve_time, ips
except Exception as e:
return None, str(e)
def run_test(self, iterations=3):
"""运行测试"""
print(f"\nDNS解析速度测试 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 80)
for domain in self.domains:
print(f"\n📌 Domain: {domain}")
print("-" * 80)
domain_results = {}
for dns in self.dns_servers:
times = []
ips = set()
for _ in range(iterations):
resolve_time, result = self.resolve_with_dns(domain, dns)
if resolve_time:
times.append(resolve_time)
if isinstance(result, list):
ips.update(result)
if times:
avg_time = statistics.mean(times)
min_time = min(times)
max_time = max(times)
print(f" DNS {dns:15s}:")
print(f" 平均: {avg_time:6.2f}ms | 最小: {min_time:6.2f}ms | 最大: {max_time:6.2f}ms")
print(f" IP: {', '.join(ips)}")
domain_results[dns] = {
'avg': avg_time,
'min': min_time,
'max': max_time,
'ips': list(ips)
}
else:
print(f" DNS {dns:15s}: ❌ 解析失败")
domain_results[dns] = {'error': 'Resolution failed'}
self.results[domain] = domain_results
return self.results
def save_results(self, filename="dns_monitor_results.json"):
"""保存结果到文件"""
with open(filename, 'w', encoding='utf-8') as f:
json.dump({
'timestamp': datetime.now().isoformat(),
'results': self.results
}, f, ensure_ascii=False, indent=2)
print(f"\n结果已保存到: {filename}")
def main():
parser = argparse.ArgumentParser(description='DNS解析速度监控')
parser.add_argument('--domains', nargs='+', default=['www.baidu.com', 'www.google.com'],
help='要测试的域名列表')
parser.add_argument('--dns-servers', nargs='+', default=None,
help='DNS服务器列表')
parser.add_argument('--iterations', type=int, default=3,
help='每个DNS的测试次数')
parser.add_argument('--save', action='store_true',
help='保存结果到文件')
args = parser.parse_args()
monitor = DNSMonitor(args.domains, args.dns_servers)
results = monitor.run_test(args.iterations)
if args.save:
monitor.save_results()
if __name__ == "__main__":
# 安装依赖:pip install dnspython
main()
Shell脚本 - 简单版
#!/bin/bash
# DNS解析速度监控 - Shell版本
DOMAINS=("www.baidu.com" "www.google.com" "www.github.com")
DNS_SERVERS=("8.8.8.8" "1.1.1.1" "114.114.114.114")
ITERATIONS=3
echo "DNS解析速度监控"
echo "开始时间: $(date)"
echo "=========================================="
for domain in "${DOMAINS[@]}"; do
echo -e "\n📌 域名: $domain"
echo "------------------------------------------"
for dns in "${DNS_SERVERS[@]}"; do
total_time=0
success=true
for ((i=1; i<=ITERATIONS; i++)); do
start_time=$(date +%s%N)
# 使用指定DNS解析
result=$(dig @$dns $domain +short +timeout=5 2>/dev/null)
if [ $? -ne 0 ] || [ -z "$result" ]; then
success=false
break
fi
end_time=$(date +%s%N)
elapsed=$(( ($end_time - $start_time) / 1000000 )) # 转换为毫秒
total_time=$((total_time + elapsed))
done
if [ "$success" = true ]; then
avg_time=$((total_time / ITERATIONS))
echo " DNS $dns : ${avg_time}ms - IP: $(echo "$result" | head -1)"
else
echo " DNS $dns : 解析失败 ❌"
fi
done
done
echo -e "\n完成时间: $(date)"
持续监控脚本 - 带报警功能
#!/usr/bin/env python3
"""
持续DNS监控 - 带报警和日志功能
"""
import dns.resolver
import time
import logging
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
class DNSContinuousMonitor:
def __init__(self, domain, threshold_ms=1000, check_interval=60):
self.domain = domain
self.threshold = threshold_ms
self.interval = check_interval
self.setup_logging()
def setup_logging(self):
"""配置日志"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(f'dns_monitor_{datetime.now().strftime("%Y%m%d")}.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
def check_dns(self):
"""检查DNS解析"""
resolver = dns.resolver.Resolver()
resolver.timeout = 5
resolver.lifetime = 5
start_time = time.time()
try:
answers = resolver.resolve(self.domain, 'A')
resolve_time = (time.time() - start_time) * 1000
ips = [str(r) for r in answers]
self.logger.info(f"解析成功 | 时间: {resolve_time:.2f}ms | IP: {', '.join(ips)}")
if resolve_time > self.threshold:
self.logger.warning(f"⚠️ 解析超时告警: {resolve_time:.2f}ms > {self.threshold}ms")
self.send_alert(f"DNS解析超时: {resolve_time:.2f}ms")
return True
except Exception as e:
self.logger.error(f"解析失败: {str(e)}")
self.send_alert(f"DNS解析失败: {str(e)}")
return False
def send_alert(self, message):
"""发送告警(示例:打印,实际可改为邮件/短信等)"""
print(f"🚨 告警: {message}")
# 这里可以添加实际的告警逻辑
# 发送邮件、调用API等
def run(self):
"""持续监控运行"""
self.logger.info(f"开始监控 {self.domain}")
self.logger.info(f"告警阈值: {self.threshold}ms")
self.logger.info(f"检查间隔: {self.interval}秒")
self.logger.info("=" * 50)
try:
while True:
self.check_dns()
time.sleep(self.interval)
except KeyboardInterrupt:
self.logger.info("监控已停止")
if __name__ == "__main__":
monitor = DNSContinuousMonitor(
domain="www.example.com",
threshold_ms=500, # 500ms告警阈值
check_interval=10 # 10秒检查一次
)
monitor.run()
使用方法
-
基础脚本:
python dns_monitor.py www.google.com --count 5 python dns_monitor.py www.baidu.com --dns 8.8.8.8
-
高级脚本:
python dns_advanced.py --domains www.baidu.com www.google.com --iterations 5 --save
-
Shell脚本:
chmod +x dns_monitor.sh ./dns_monitor.sh
-
持续监控:
python dns_continuous.py
监控指标说明
- 解析时间: DNS查询的响应时间(毫秒)
- 成功率: 成功解析的比例
- IP变化: 监控IP地址变化情况
- 不同DNS对比: 比较各DNS服务器的性能
这些脚本可以根据你的具体需求进行修改和扩展。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播