要解决这个问题,可以使用 AWS SDK 中提供的 AWS Systems Manager 的 createKeyPair
方法来请求新的主机密钥。
以下是一个使用 AWS SDK for Python(Boto3)的示例代码:
import boto3
def create_key_pair(instance_id):
ec2_client = boto3.client('ec2')
ssm_client = boto3.client('ssm')
# 获取 EC2 实例的区域和密钥名称
response = ec2_client.describe_instances(InstanceIds=[instance_id])
region = response['Reservations'][0]['Instances'][0]['Placement']['AvailabilityZone'][:-1]
key_name = response['Reservations'][0]['Instances'][0]['KeyName']
# 使用 Systems Manager 创建新的主机密钥
response = ssm_client.create_key_pair(
KeyPairName=key_name,
Tags=[
{
'Key': 'CreatedBy',
'Value': 'AutomatedScript'
},
]
)
# 获取新的密钥对的公钥
public_key = response['KeyMaterial']
# 更新 EC2 实例的密钥对
ec2_client.modify_instance_attribute(
InstanceId=instance_id,
KeyName=key_name
)
return public_key
# 示例用法
instance_id = 'your-instance-id'
new_public_key = create_key_pair(instance_id)
print(new_public_key)
请确保已经安装了 AWS SDK for Python(Boto3),并按照您的实际情况替换示例代码中的实例 ID。