How to execute commands on AWS Instance using Boto3

后端 未结 6 1470
一生所求
一生所求 2021-01-11 12:01

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

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

6条回答
  •  旧时难觅i
    2021-01-11 12:11

    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

    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 docs For information on SSM itself refer AWS docs

提交回复
热议问题