【问题标题】:How to execute commands on AWS Instance using Boto3如何使用 Boto3 在 AWS Instance 上执行命令
【发布时间】:2018-07-11 09:29:57
【问题描述】:

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

我在几个地方读到过“boto.manage.cmdshell”,但它在 Boto3 中已被弃用。

感谢任何帮助。

问候, 索拉布

【问题讨论】:

    标签: python amazon-web-services boto3


    【解决方案1】:
    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)
    

    【讨论】:

    • 请提供一些上下文,以便读者理解代码而不是复制+粘贴
    【解决方案2】:
    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 是一个假装的 ec2 实例 ID。 我把它放在 OutputS3KeyPrefix 中,以获得一个独特的地方来存储桶中的日志。

    你可以这样安装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
        )
    

    【讨论】:

    • 感谢您发布此解决方案。作为在这里有经验的人,鉴于 paramiko 的简单性,您是否会提倡使用 paramiko 而不是 SSM? github 问题中的开发人员在这里:github.com/boto/boto3/issues/328 似乎更喜欢它而不是 SSM 来执行 shell 脚本。
    • 我已经使用 cloudformation 模板进行部署。它有助于明确您已经在 cf 控制台中部署的内容。
    【解决方案3】:

    我知道我正在回答有点旧的线程。即使在那个时候,我也不确定 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)
    

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

    【讨论】:

    • 如何使用 AWS-RunPowerShellScript 创建用户名和密码?有谁能帮我做吗?
    【解决方案4】:

    没有。 boto 中的boto.manage.cmdshell 功能未迁移到boto3。原始的boto.manage.cmdshell 功能使用Paramiko,如果您想在boto3 中使用SSH 功能,可以直接与boto3 一起使用。

    这是关于此主题的boto3 github issue

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

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

    【讨论】:

    • 非常感谢。我要试试 Paramiko。
    • 还可以查看最近发布的 EC2 运行命令:aws.amazon.com/blogs/aws/…。该博客表明它在 boto3 和 awscli 中得到支持,尽管我还没有找到它。这是常见问题解答:aws.amazon.com/ec2/run-command/faqs
    • @Gil 你能补充更多细节吗,什么不适合你?
    【解决方案5】:

    改变

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

    command_id = context.aws_request_id
    

    【讨论】:

      【解决方案6】:

      Documentation 说:

      aws_request_id

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

      变化:

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

      为:

      command_id = context.aws_request_id
      

      【讨论】:

      • 为什么要两次发布相同的答案?
      猜你喜欢
      • 2020-04-20
      • 2017-04-21
      • 2020-05-11
      • 2016-12-09
      • 1970-01-01
      • 2017-07-27
      • 2015-09-27
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多