使用Python中的Boto3向AmazonEC2实例发送命令

2024-03-29 12:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我能够使用以下代码,使用boto3从Amazon EC2上的图像创建一个实例:

ec2 = boto3.client('ec2',region_name = 'eu-west-2')
instance = ec2.run_instances(
           ImageId='ami-011c936382e4e2g9c',
           MinCount=1,
           MaxCount=1,
           InstanceType = 't2.micro',
           SecurityGroupIds= ['sg-0c08ad7b130e3hf3',],)
id = str(instance['Instances'][0]['InstanceId'])

这很好,但是我希望向实例发送一个简单的命令,该命令将执行存储在实例上的python脚本。据我所知,boto3内置了AWS命令行功能,因此我不必使用SSH连接实例;我应该可以通过boto3发送命令。然而,在尝试了以下代码的不同变体之后,我正在努力做到这一点:

client = boto3.client('ssm',region_name='eu-west-2')
commands = ['echo "hello world" > hello.txt'] #this would be replaced by the command to execute the python script
instance_id = [id] #id being the instance id established from above
response = client.send_command(DocumentName='AWS-RunShellScript',
                               Parameters= 'commands':commands},
                               InstanceIds=instance_id,)

我知道服务器启动etc需要时间,但这不是问题所在。当我知道服务器确实准备好运行时,我在一个大延迟之后执行了第二段代码

如前所述,我认为这可能与我通常需要使用的pem文件有关,以便将/ssh放入实例中,因为我的代码中没有配置该文件。任何线索都将不胜感激


Tags: the实例instance代码name命令clientaws