Skip to content

Instantly share code, notes, and snippets.

@ensean
Created April 29, 2026 08:28
Show Gist options
  • Select an option

  • Save ensean/9c7b035c05a292408450064bdaf87f6c to your computer and use it in GitHub Desktop.

Select an option

Save ensean/9c7b035c05a292408450064bdaf87f6c to your computer and use it in GitHub Desktop.
query dns
#!/usr/bin/env python3
"""批量查询所有 HostedZone 的 DNSQueries 指标,绕过 Metrics Insights 500 条限制"""
import boto3
from datetime import datetime, timezone, timedelta
PROFILE = "default"
REGION = "us-east-1"
PERIOD = 3600
session = boto3.Session(profile_name=PROFILE)
route53 = session.client("route53")
cloudwatch = session.client("cloudwatch", region_name=REGION)
# 1. 获取所有 HostedZone ID
zone_ids = []
paginator = route53.get_paginator("list_hosted_zones")
for page in paginator.paginate():
for zone in page["HostedZones"]:
zone_ids.append(zone["Id"].replace("/hostedzone/", ""))
print(f"共 {len(zone_ids)} 个 HostedZone")
# 2. 分批查询(每批最多 500 个)
end_time = datetime.now(timezone.utc)
start_time = end_time - timedelta(days=1)
results = {}
for i in range(0, len(zone_ids), 500):
batch = zone_ids[i:i + 500]
batch_num = i // 500 + 1
print(f"查询批次 {batch_num}: zone {i+1} ~ {i+len(batch)}")
queries = [
{
"Id": f"q{j}",
"MetricStat": {
"Metric": {
"Namespace": "AWS/Route53",
"MetricName": "DNSQueries",
"Dimensions": [{"Name": "HostedZoneId", "Value": zid}],
},
"Period": PERIOD,
"Stat": "Sum",
},
}
for j, zid in enumerate(batch)
]
resp = cloudwatch.get_metric_data(
StartTime=start_time,
EndTime=end_time,
MetricDataQueries=queries,
)
for r in resp["MetricDataResults"]:
total = sum(r["Values"]) if r["Values"] else 0
if total > 0:
results[r["Label"]] = int(total)
# 3. 输出结果
print(f"\n=== DNSQueries 汇总(过去24小时)===")
for zone_id, total in sorted(results.items(), key=lambda x: -x[1]):
print(f" {zone_id}\t{total}")
if not results:
print(" 无数据")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment