首页 > 解决方案 > 在 Python 中使用 Boto3 向 Amazon EC2 实例发送命令

问题描述

我可以使用 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,)

我知道服务器启动等需要时间,但这不是问题。当我知道服务器确实准备好运行时,我已经在很长一段时间后执行了第二段代码。

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

标签: pythonamazon-web-servicesboto3

解决方案


推荐阅读