如何使用Python Boto3下载AWS Windows EC2实例的.rdp文件
批量导出AWS Windows EC2实例RDP文件的Boto3实现方案
前置准备
- 本地已经配置好AWS身份凭证,对应账号拥有EC2实例的读取权限
- 已安装Python依赖库:
pip install boto3
核心逻辑
RDP文件本质是固定格式的纯文本配置,无需调用AWS特殊接口生成,只需提取Windows EC2实例的公网访问地址,按标准RDP模板生成文件即可:
- 调用EC2接口筛选所有平台为Windows的实例
- 遍历实例提取实例ID、公网IP/公网DNS信息
- 填充RDP模板后以
[实例标识].rdp命名保存到本地
完整可运行代码
import boto3 import os # 配置本地保存RDP文件的目录 SAVE_DIR = "./aws_rdp_files" os.makedirs(SAVE_DIR, exist_ok=True) # 初始化EC2客户端,默认读取本地AWS凭证配置,region替换为你自己的EC2所在区域 ec2 = boto3.client('ec2', region_name='us-east-1') # 筛选所有Windows系统的EC2实例 response = ec2.describe_instances( Filters=[ { 'Name': 'platform', 'Values': ['windows'] }, { 'Name': 'instance-state-name', 'Values': ['running'] # 只筛选运行中的实例,不需要可以删掉该过滤条件 } ] ) # 标准RDP配置模板,可按需添加自定义配置项 RDP_TEMPLATE = """full address:s:{ip} username:s:Administrator screen mode id:i:1 desktopwidth:i:1920 desktopheight:i:1080 auto connect:i:1 authentication level:i:2 prompt for credentials:i:0 negotiate security layer:i:1 remoteapplicationmode:i:0 alternate shell:s: shell working directory:s: disable wallpaper:i:0 disable full window drag:i:0 disable menu anims:i:0 disable themes:i:0 disable cursor setting:i:0 bitmapcachepersistenable:i:1 """ # 遍历生成RDP文件 for reservation in response['Reservations']: for instance in reservation['Instances']: instance_id = instance['InstanceId'] # 优先取公网IP,没有的话取私有IP,可按需调整 public_ip = instance.get('PublicIpAddress') or instance.get('PrivateIpAddress') if not public_ip: print(f"跳过实例 {instance_id}:无可用IP地址") continue # 提取实例名称标签作为文件名,没有的话用实例ID instance_name = instance_id for tag in instance.get('Tags', []): if tag['Key'] == 'Name': instance_name = tag['Value'] break # 生成文件内容 rdp_content = RDP_TEMPLATE.format(ip=public_ip) # 保存文件,文件名处理掉特殊字符避免报错 file_name = f"{instance_name.replace('/', '_').replace(' ', '_')}_{instance_id}.rdp" file_path = os.path.join(SAVE_DIR, file_name) with open(file_path, 'w', encoding='utf-8') as f: f.write(rdp_content) print(f"已生成RDP文件:{file_path}")
注意事项
- 代码中的
region_name请替换为你EC2实例实际所在的AWS区域 - 如果你的Windows实例自定义了管理员账号,把模板里的
username:s:Administrator修改为对应账号即可 - RDP模板的参数可按需调整,比如把
screen mode id:i:1改为screen mode id:i:2就是默认全屏打开 - 如果实例部署在私有子网,本地已经通过VPN/专线连通私有网络,可以把IP获取逻辑改为优先取私有IP
- 代码默认不会把密码写入RDP文件,打开时手动输入密码更安全,若需要自动填充密码,可以调用
get_password_data接口配合密钥对pem文件解密后写入模板即可
内容的提问来源于stack exchange,提问作者radhika
相关产品推荐
相关产品推荐

