作者: RJ.Wang
邮箱: wangrenjun@gmail.com
创建时间: 2025-01-07
更新时间: 2025-01-07
📋 概述
本指南详细介绍如何获取 AWS 中国宁夏区域(cn-northwest-1)的 IP 地址段,包括官方方法、API 调用和自动化脚本。
🎯 获取方法概览
flowchart TD
Start([🚀 开始获取 IP 段]) --> Method{🤔 选择获取方法}
Method -->|官方文件| Official[📄 下载官方 JSON 文件]
Method -->|API 调用| API[🔌 使用 AWS API]
Method -->|自动化| Script[🤖 运行自动化脚本]
Official --> Parse1[📊 解析 JSON 数据]
API --> Parse2[📊 解析 API 响应]
Script --> Parse3[📊 自动解析输出]
Parse1 --> Filter[🔍 筛选宁夏区域]
Parse2 --> Filter
Parse3 --> Filter
Filter --> Output[📋 输出 IP 段列表]
Output --> End([🎉 完成])
classDef startEnd fill:#e8f5e8,stroke:#388e3c
classDef process fill:#e3f2fd,stroke:#1976d2
classDef decision fill:#fff3e0,stroke:#f57c00
class Start,End startEnd
class Official,API,Script,Parse1,Parse2,Parse3,Filter,Output process
class Method decision
📄 方法一:官方 JSON 文件
1.1 下载官方文件
AWS 官方提供的 IP 段文件:
# 下载最新的 IP 段文件
curl -o aws-ip-ranges.json https://ip-ranges.amazonaws.com/ip-ranges.json
# 查看文件信息
ls -la aws-ip-ranges.json
1.2 解析宁夏区域 IP 段
# 使用 jq 筛选宁夏区域的 IPv4 地址段
cat aws-ip-ranges.json | jq -r '.prefixes[] | select(.region=="cn-northwest-1") | .ip_prefix'
# 筛选特定服务的 IP 段(如 EC2)
cat aws-ip-ranges.json | jq -r '.prefixes[] | select(.region=="cn-northwest-1" and .service=="EC2") | .ip_prefix'
# 获取 IPv6 地址段
cat aws-ip-ranges.json | jq -r '.ipv6_prefixes[] | select(.region=="cn-northwest-1") | .ipv6_prefix'
1.3 按服务分类输出
# 创建按服务分类的脚本
cat > parse_ningxia_ips.sh << 'EOF'
#!/bin/bash
echo "=== AWS 宁夏区域 (cn-northwest-1) IP 段 ==="
echo "生成时间: $(date)"
echo ""
# 下载最新文件
curl -s -o aws-ip-ranges.json https://ip-ranges.amazonaws.com/ip-ranges.json
# 获取所有服务列表
services=$(cat aws-ip-ranges.json | jq -r '.prefixes[] | select(.region=="cn-northwest-1") | .service' | sort -u)
echo "📋 可用服务:"
echo "$services"
echo ""
# 按服务输出 IP 段
for service in $services; do
echo "🔧 $service 服务 IP 段:"
cat aws-ip-ranges.json | jq -r ".prefixes[] | select(.region==\"cn-northwest-1\" and .service==\"$service\") | .ip_prefix"
echo ""
done
# IPv6 地址段
echo "🌐 IPv6 地址段:"
cat aws-ip-ranges.json | jq -r '.ipv6_prefixes[] | select(.region=="cn-northwest-1") | .ipv6_prefix'
# 清理临时文件
rm aws-ip-ranges.json
EOF
chmod +x parse_ningxia_ips.sh
🔌 方法二:AWS CLI API 调用
2.1 使用 AWS CLI
# 确保已配置中国区 profile
aws --profile c5611 sts get-caller-identity
# 获取 VPC 相关 IP 段
aws --profile c5611 ec2 describe-regions --region cn-northwest-1
# 获取可用区信息
aws --profile c5611 ec2 describe-availability-zones --region cn-northwest-1
2.2 获取 VPC CIDR 信息
# 列出所有 VPC 及其 CIDR 块
aws --profile c5611 ec2 describe-vpcs --region cn-northwest-1 \
--query 'Vpcs[*].{VpcId:VpcId,CidrBlock:CidrBlock,State:State}' \
--output table
# 获取子网 CIDR 信息
aws --profile c5611 ec2 describe-subnets --region cn-northwest-1 \
--query 'Subnets[*].{SubnetId:SubnetId,VpcId:VpcId,CidrBlock:CidrBlock,AvailabilityZone:AvailabilityZone}' \
--output table
🤖 方法三:自动化 Python 脚本
3.1 创建获取脚本
#!/usr/bin/env python3
"""
AWS 宁夏区域 IP 段获取工具
作者: RJ.Wang
邮箱: wangrenjun@gmail.com
创建时间: 2025-01-07
"""
import json
import requests
from datetime import datetime
import argparse
def get_aws_ip_ranges():
"""获取 AWS 官方 IP 段数据"""
url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"❌ 获取 IP 段数据失败: {e}")
return None
def filter_ningxia_ips(data, service_filter=None):
"""筛选宁夏区域的 IP 段"""
region = "cn-northwest-1"
# IPv4 地址段
ipv4_prefixes = []
for prefix in data.get('prefixes', []):
if prefix.get('region') == region:
if service_filter is None or prefix.get('service') == service_filter:
ipv4_prefixes.append({
'ip_prefix': prefix['ip_prefix'],
'service': prefix['service']
})
# IPv6 地址段
ipv6_prefixes = []
for prefix in data.get('ipv6_prefixes', []):
if prefix.get('region') == region:
if service_filter is None or prefix.get('service') == service_filter:
ipv6_prefixes.append({
'ipv6_prefix': prefix['ipv6_prefix'],
'service': prefix['service']
})
return ipv4_prefixes, ipv6_prefixes
def print_results(ipv4_prefixes, ipv6_prefixes, service_filter=None):
"""打印结果"""
print("=" * 60)
print("🏢 AWS 宁夏区域 (cn-northwest-1) IP 段")
print(f"📅 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
if service_filter:
print(f"🔧 服务筛选: {service_filter}")
print("=" * 60)
# 按服务分组
services = {}
# 处理 IPv4
for item in ipv4_prefixes:
service = item['service']
if service not in services:
services[service] = {'ipv4': [], 'ipv6': []}
services[service]['ipv4'].append(item['ip_prefix'])
# 处理 IPv6
for item in ipv6_prefixes:
service = item['service']
if service not in services:
services[service] = {'ipv4': [], 'ipv6': []}
services[service]['ipv6'].append(item['ipv6_prefix'])
# 输出结果
for service, ips in sorted(services.items()):
print(f"\n🔧 {service} 服务:")
if ips['ipv4']:
print(" 📍 IPv4 地址段:")
for ip in sorted(ips['ipv4']):
print(f" {ip}")
if ips['ipv6']:
print(" 🌐 IPv6 地址段:")
for ip in sorted(ips['ipv6']):
print(f" {ip}")
# 统计信息
total_ipv4 = len(ipv4_prefixes)
total_ipv6 = len(ipv6_prefixes)
total_services = len(services)
print(f"\n📊 统计信息:")
print(f" 🔢 IPv4 地址段: {total_ipv4}")
print(f" 🔢 IPv6 地址段: {total_ipv6}")
print(f" 🔢 服务数量: {total_services}")
def save_to_file(ipv4_prefixes, ipv6_prefixes, filename):
"""保存到文件"""
data = {
'region': 'cn-northwest-1',
'generated_at': datetime.now().isoformat(),
'ipv4_prefixes': ipv4_prefixes,
'ipv6_prefixes': ipv6_prefixes
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"💾 结果已保存到: {filename}")
def main():
parser = argparse.ArgumentParser(description='获取 AWS 宁夏区域 IP 段')
parser.add_argument('--service', help='筛选特定服务 (如: EC2, S3, CLOUDFRONT)')
parser.add_argument('--output', help='输出文件名 (JSON 格式)')
args = parser.parse_args()
# 获取数据
print("🔄 正在获取 AWS IP 段数据...")
data = get_aws_ip_ranges()
if not data:
return 1
# 筛选宁夏区域
print("🔍 正在筛选宁夏区域数据...")
ipv4_prefixes, ipv6_prefixes = filter_ningxia_ips(data, args.service)
# 显示结果
print_results(ipv4_prefixes, ipv6_prefixes, args.service)
# 保存到文件
if args.output:
save_to_file(ipv4_prefixes, ipv6_prefixes, args.output)
return 0
if __name__ == "__main__":
exit(main())
3.2 使用脚本
# 保存脚本
cat > get_ningxia_ips.py << 'EOF'
# [上面的 Python 脚本内容]
EOF
chmod +x get_ningxia_ips.py
# 获取所有 IP 段
python3 get_ningxia_ips.py
# 筛选特定服务
python3 get_ningxia_ips.py --service EC2
# 保存到文件
python3 get_ningxia_ips.py --output ningxia_ips.json
📊 常见服务 IP 段
4.1 主要服务列表
graph TB
subgraph "🏢 AWS 宁夏区域服务"
EC2[🖥️ EC2<br/>弹性计算云]
S3[📦 S3<br/>对象存储]
RDS[💾 RDS<br/>关系数据库]
ELB[⚖️ ELB<br/>负载均衡]
CF[🌐 CloudFront<br/>内容分发]
API[🔌 API Gateway<br/>API 网关]
end
classDef service fill:#e3f2fd,stroke:#1976d2
class EC2,S3,RDS,ELB,CF,API service
4.2 快速查询命令
# EC2 实例 IP 段
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | \
jq -r '.prefixes[] | select(.region=="cn-northwest-1" and .service=="EC2") | .ip_prefix'
# S3 服务 IP 段
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | \
jq -r '.prefixes[] | select(.region=="cn-northwest-1" and .service=="S3") | .ip_prefix'
# CloudFront IP 段(全球)
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | \
jq -r '.prefixes[] | select(.service=="CLOUDFRONT") | .ip_prefix'
🔧 实用工具脚本
5.1 一键获取脚本
#!/bin/bash
# 一键获取宁夏区域 IP 段
echo "🚀 开始获取 AWS 宁夏区域 IP 段..."
# 创建输出目录
mkdir -p aws_ningxia_ips
cd aws_ningxia_ips
# 下载数据
echo "📥 下载官方数据..."
curl -s -o aws-ip-ranges.json https://ip-ranges.amazonaws.com/ip-ranges.json
# 生成报告
echo "📊 生成 IP 段报告..."
cat > ningxia_ip_report.txt << EOF
AWS 宁夏区域 (cn-northwest-1) IP 段报告
生成时间: $(date)
数据来源: https://ip-ranges.amazonaws.com/ip-ranges.json
=== IPv4 地址段 ===
EOF
# 按服务分类输出
services=$(cat aws-ip-ranges.json | jq -r '.prefixes[] | select(.region=="cn-northwest-1") | .service' | sort -u)
for service in $services; do
echo "" >> ningxia_ip_report.txt
echo "[$service 服务]" >> ningxia_ip_report.txt
cat aws-ip-ranges.json | jq -r ".prefixes[] | select(.region==\"cn-northwest-1\" and .service==\"$service\") | .ip_prefix" >> ningxia_ip_report.txt
done
# IPv6 地址段
echo "" >> ningxia_ip_report.txt
echo "=== IPv6 地址段 ===" >> ningxia_ip_report.txt
cat aws-ip-ranges.json | jq -r '.ipv6_prefixes[] | select(.region=="cn-northwest-1") | .ipv6_prefix' >> ningxia_ip_report.txt
# 生成 CSV 格式
echo "📋 生成 CSV 格式..."
echo "IP段,服务,协议版本" > ningxia_ips.csv
cat aws-ip-ranges.json | jq -r '.prefixes[] | select(.region=="cn-northwest-1") | "\(.ip_prefix),\(.service),IPv4"' >> ningxia_ips.csv
cat aws-ip-ranges.json | jq -r '.ipv6_prefixes[] | select(.region=="cn-northwest-1") | "\(.ipv6_prefix),\(.service),IPv6"' >> ningxia_ips.csv
# 清理
rm aws-ip-ranges.json
echo "✅ 完成!生成的文件:"
echo " 📄 ningxia_ip_report.txt - 详细报告"
echo " 📊 ningxia_ips.csv - CSV 格式数据"
5.2 定时更新脚本
#!/bin/bash
# 定时更新 AWS IP 段数据
SCRIPT_DIR="/path/to/aws_ip_scripts"
LOG_FILE="$SCRIPT_DIR/update.log"
echo "$(date): 开始更新 AWS 宁夏区域 IP 段" >> $LOG_FILE
cd $SCRIPT_DIR
# 备份旧数据
if [ -f "ningxia_ips.json" ]; then
mv ningxia_ips.json "ningxia_ips_$(date +%Y%m%d_%H%M%S).json.bak"
fi
# 获取新数据
python3 get_ningxia_ips.py --output ningxia_ips.json >> $LOG_FILE 2>&1
if [ $? -eq 0 ]; then
echo "$(date): 更新成功" >> $LOG_FILE
else
echo "$(date): 更新失败" >> $LOG_FILE
fi
# 清理旧备份(保留最近 7 天)
find . -name "ningxia_ips_*.json.bak" -mtime +7 -delete
⚠️ 注意事项
6.1 数据更新频率
- 🔄 AWS 官方 IP 段文件不定期更新
- 📅 建议每周检查一次是否有更新
- 🚨 重要变更时 AWS 会发布通知
6.2 使用限制
- 🌐 IP 段仅适用于cn-northwest-1 区域
- 🔒 某些服务可能有额外的 IP 限制
- ⚖️ 负载均衡器 IP 可能动态变化
6.3 安全考虑
- 🛡️ 不要仅依赖 IP 段进行安全控制
- 🔐 结合使用安全组和NACL
- 📊 定期审查和更新防火墙规则
🔗 相关资源
官方文档
工具和 API
最后更新: 2025-01-07