Ashish Bhumkar
Ashish Bhumkar

Reputation: 115

Boto3: create, execute shell command, terminate on ec2 instance

I am newbie to EC2 and boto. I have to create an EC2 running instance, where I can send a command with S3 file and execute a shell script.

I searched a lot and found a way with boto and paramiko. I don't know, whether it is possible to run a shell script in ec2 instance using boto3. Any clue or example in this reference will be a great help.

Thank you!

Upvotes: 2

Views: 4255

Answers (2)

thclark
thclark

Reputation: 5500

There's a difference between Boto and Boto3. The question specifies boto, but the question title says Boto3.

The accepted answer is correct for boto. But, for boto3, this question is answered here :)

Upvotes: 2

Piyush Patil
Piyush Patil

Reputation: 14533

The boto.manage.cmdshell module can be used to do this. To use it, you must have the paramiko package installed. A simple example of it's use:

import boto.ec2
from boto.manage.cmdshell import sshclient_from_instance

# Connect to your region of choice
conn = boto.ec2.connect_to_region('us-west-2')

# Find the instance object related to my instanceId
instance = conn.get_all_instances(['i-12345678'])[0].instances[0]

# Create an SSH client for our instance
#    key_path is the path to the SSH private key associated with instance
#    user_name is the user to login as on the instance (e.g. ubuntu, ec2-user, etc.)
ssh_client = sshclient_from_instance(instance,
                                     '<path to SSH keyfile>',
                                     user_name='ec2-user')
# Run the command. Returns a tuple consisting of:
#    The integer status of the command
#    A string containing the output of the command
#    A string containing the stderr output of the command
status, stdout, stderr = ssh_client.run('ls -al')

Upvotes: 1

Related Questions