python - 在 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 放入实例中,因为我的代码中的任何地方都没有配置它。任何线索将不胜感激!
解决方案
推荐阅读
- python - python列表中的选项卡\ n
- c# - 剃须刀页面,如何将 json 序列化字符串传递给模型属性
- amcharts - Amcharts V4 用已知值在系列上标记值
- c# - 单击删除按钮时从 Datagridview 中删除选定的行并同时删除 XML 节点
- firebase - 如何在 Firestore 中使用 Flutter(Web 应用)流构建器
- python-3.x - 在python中的字典中写入csv文件中的列
- python - 为什么我的 for 循环不返回任何内容?
- javascript - 如何只使用一个到 MongoDB 的连接?
- angularjs - 您如何通过对象的对象进行 ng-repeat 以显示键和值?
- ansible - 在 Ansible 中为每个环境分配变量的问题