如何使用Boto3将EC2实例详情导出为XLSX格式?
导出EC2实例详情到XLSX格式的方法
你可以借助Python的openpyxl或pandas库,结合Boto3获取的EC2数据生成XLSX文件,以下是两种可行方案:
方案一:使用openpyxl库(原生操作Excel)
- 先安装依赖:
pip install openpyxl boto3
- 示例代码:
import boto3 from openpyxl import Workbook # 初始化EC2客户端 ec2 = boto3.client('ec2') # 获取所有EC2实例 response = ec2.describe_instances() # 提取需要的实例字段(可根据需求调整) instance_data = [] headers = ['实例ID', '名称', '实例类型', '状态', '私有IP', '公有IP', '区域'] for reservation in response['Reservations']: for instance in reservation['Instances']: # 从标签中提取实例名称 instance_name = next((tag['Value'] for tag in instance.get('Tags', []) if tag['Key'] == 'Name'), '无名称') # 整理单条实例数据 instance_info = [ instance['InstanceId'], instance_name, instance['InstanceType'], instance['State']['Name'], instance.get('PrivateIpAddress', '无'), instance.get('PublicIpAddress', '无'), ec2._endpoint.host.split('.')[1] # 获取当前区域 ] instance_data.append(instance_info) # 创建Excel工作簿并写入数据 wb = Workbook() ws = wb.active ws.title = "EC2实例详情" # 写入表头 ws.append(headers) # 写入实例数据 for row in instance_data: ws.append(row) # 保存文件 wb.save('ec2_instances.xlsx')
方案二:使用pandas库(更简洁高效)
pandas适合快速处理结构化数据,导出Excel的代码更简洁,数据量较大时优势明显:
- 安装依赖:
pip install pandas openpyxl boto3
- 示例代码:
import boto3 import pandas as pd # 初始化EC2客户端 ec2 = boto3.client('ec2') # 获取所有EC2实例 response = ec2.describe_instances() # 整理实例数据为列表字典格式 instance_list = [] for reservation in response['Reservations']: for instance in reservation['Instances']: instance_name = next((tag['Value'] for tag in instance.get('Tags', []) if tag['Key'] == 'Name'), '无名称') instance_list.append({ '实例ID': instance['InstanceId'], '名称': instance_name, '实例类型': instance['InstanceType'], '状态': instance['State']['Name'], '私有IP': instance.get('PrivateIpAddress', '无'), '公有IP': instance.get('PublicIpAddress', '无'), '区域': ec2._endpoint.host.split('.')[1] }) # 转为DataFrame并导出为XLSX df = pd.DataFrame(instance_list) df.to_excel('ec2_instances_pandas.xlsx', sheet_name='EC2实例详情', index=False)
注意事项
- 确保环境已配置AWS凭证(通过
~/.aws/credentials文件、环境变量或IAM角色) - 可根据需求调整提取字段,比如添加VPC ID、子网ID、启动时间等
- 多区域环境下,可循环遍历所有区域调用
describe_instances接口
内容的提问来源于stack exchange,提问作者Chakri
相关产品推荐
相关产品推荐

