Python 如何使用 Boto3 在 AWS 实例上执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34028219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:22:06  来源:igfitidea点击:

How to execute commands on AWS Instance using Boto3

pythonamazon-web-servicesboto3

提问by sdeshpande

Can anyone tell me if we can execute Shell Commands using Boto3 on Launched AWS instance.

谁能告诉我我们是否可以在启动的 AWS 实例上使用 Boto3 执行 Shell 命令。

I read at few places about "boto.manage.cmdshell" but it is deprecated in Boto3.

我在几个地方读到了有关“boto.manage.cmdshell”的信息,但它在 Boto3 中已被弃用。

Appreciate any help.

感谢任何帮助。

Regards, Saurabh

问候, 索拉布

回答by gene_wood

No. The boto.manage.cmdshellfunctionality in boto was not migrated to boto3. The original boto.manage.cmdshellfunctionality used Paramikowhich you could use directly with boto3 if you want to have SSH functionality with boto3.

boto.manage.cmdshell。boto 中的功能未迁移到 boto3。原来boto.manage.cmdshell使用的功能的paramiko您可以直接与boto3,如果你想与boto3 SSH功能使用。

Here's a boto3 github issueon this topic.

这是关于此主题的boto3 github 问题

As @jarmod points out there is new AWS functionalityas of October 2015 that enables you to run commands on Windows systems using AWS EC2 SSM. You can access this in boto3 with the boto3 SSM clientas of botocore version 1.3.1.

正如@jarmod 指出的那样,截至 2015 年 10 月,AWS 的新功能使您能够使用AWS EC2 SSM在 Windows 系统上运行命令。从 botocore 版本 1.3.1开始,您可以使用boto3 SSM 客户端在 boto3 中访问它。

Here's a boto3 github issueon supporting "EC2 Run Command"

这是关于支持“EC2 运行命令”的boto3 github 问题

回答by ddtraveller

ssm = boto3.client('ssm' )    
testCommand = ssm.send_command( InstanceIds=[ 'i-123123123123' ], DocumentName='AWS-RunShellScript', Comment='la la la', OutputS3BucketName='myOutputS3Bucket', OutputS3KeyPrefix='i-123123123123', Parameters={ "commands":[ "ip config" ]  } )

i-123123123123 is a pretend ec2 instance id. I put that in the OutputS3KeyPrefix to get a unique place to store logs in the bucket.

i-123123123123 是一个假装的 ec2 实例 ID。我把它放在 OutputS3KeyPrefix 中以获得一个唯一的位置来存储存储桶中的日志。

You can install the ssm agent like this;

您可以像这样安装 ssm 代理;

ec2r = boto3.resource('ec2' )
userdata = """#cloud-config
    runcmd:
     - /home/ec2-user/sudo npm run prod
     - cd /tmp
     - curl https://amazon-ssm-%s.s3.amazonaws.com/latest/linux_amd64/amazon-ssm-agent.rpm -o amazon-ssm-agent.rpm
     - yum install -y amazon-ssm-agent.rpm
""" % region   

if ssm == "on":
    instance = ec2r.create_instances( ImageId=ami, MinCount=1, MaxCount=1, KeyName=keyname, InstanceType=instancetype, 
        NetworkInterfaces=[{
        'DeviceIndex': 0,
        'AssociatePublicIpAddress': False,
        'SubnetId': mySub,
        'Groups': secGroupList,
        'AssociatePublicIpAddress': AssociatePublicIpAddress
    }],
        Monitoring={ 'Enabled': False },

        UserData=userdata,
        IamInstanceProfile={
            'Name': rolename
        },
        EbsOptimized=False
    )

回答by sumit pandit

I know I am answering to bit old thread. I am not sure even at that time SSM existed. But now you can use SSM send_command from boto3 to run commands directly on ec2 instances. Here is the sample to run PowerShell commands on EC2 instances

我知道我正在回答有点旧的话题。即使在那个时候我也不确定 SSM 是否存在。但是现在您可以使用 boto3 中的 SSM send_command 直接在 ec2 实例上运行命令。这是在 EC2 实例上运行 PowerShell 命令的示例

import boto3
ssm_client = boto3.client('ssm', region_name="us-west-2") # use region code in which you are working
response = ssm_client.send_command(
             InstanceIds=[
                "i-03########" # use instance id on which you want to execute, even multiple is allowd
                     ],
             DocumentName="AWS-RunPowerShellScript",
             Parameters={
                'commands':[
                     'ipconfig'
                       ]
                   },
             })
command_id = response['Command']['CommandId']
output = ssm_client.get_command_invocation(
      CommandId=command_id,
      InstanceId='i-03######',
    )
print(output)

For more information read boto3 SSM docsFor information on SSM itself refer AWS docs

有关更多信息,请阅读boto3 SSM 文档有关 SSM 本身的信息,请参阅 AWS 文档

回答by Joe Mantil

ssm_client = boto3.client('ssm')
response = ssm_client.send_command(
            InstanceIds=['i-03#####'],
            DocumentName="AWS-RunShellScript",
            Parameters={'commands': ['start ecs']}, )

command_id = response['Command']['CommandId']
output = ssm_client.get_command_invocation(
      CommandId=command_id,
      InstanceId='i-03######',
    )
print(output)

回答by Pablo Galeana Bailey

Change

改变

command_id = response['Command']['CommandId']

to

command_id = context.aws_request_id

回答by Pablo Galeana Bailey

Documentationsays:

文档说:

aws_request_id

AWS request ID associated with the request. This is the ID returned to the client that called the invoke method.

aws_request_id

与请求关联的 AWS 请求 ID。这是返回给调用 invoke 方法的客户端的 ID。

Change:

改变:

command_id = response['Command']['CommandId']

for:

为了:

command_id = context.aws_request_id