sdeshpande
sdeshpande

Reputation: 321

How to execute commands on an EC2 instance using boto3

Can anyone tell me if I can execute shell commands using boto3 on an AWS instance?

I read about boto.manage.cmdshell in a few places, but it is deprecated in boto3.

Upvotes: 22

Views: 57786

Answers (6)

Pablo Galeana Bailey
Pablo Galeana Bailey

Reputation: 11

Documentation says:

aws_request_id

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

Change:

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

for:

command_id = context.aws_request_id

Upvotes: 0

Pablo Galeana Bailey
Pablo Galeana Bailey

Reputation: 11

Change

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

to

command_id = context.aws_request_id

Upvotes: 1

Jose Mantilla
Jose Mantilla

Reputation: 462

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)

Upvotes: 28

sumit pandit
sumit pandit

Reputation: 1003

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

Upvotes: 9

ddtraveller
ddtraveller

Reputation: 1232

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.

You can install the ssm agent like this;

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
    )

Upvotes: 9

gene_wood
gene_wood

Reputation: 2073

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

Here's a boto3 github issue on this topic.

As @jarmod points out there is new AWS functionality as 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 client as of botocore version 1.3.1.

Here's a boto3 github issue on supporting "EC2 Run Command"

Upvotes: 2

Related Questions