Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

I want to be able to ssh into an EC2 instance and run some shell commands in it.

How do I do it in boto3?

1 Answer

0 votes
by (44.4k points)

Use this Python script to SSH to an EC2 instance and then run commands using boto3.

import boto3

import botocore

import paramiko

key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect/ssh to an instance

try:

    # Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2

    client.connect(hostname=instance_ip, username="ubuntu", pkey=key)

    # Execute a command(cmd) after connecting/ssh to an instance

    stdin, stdout, stderr = client.exec_command(cmd)

    print stdout.read()

    # close the client connection once the job is done

    client.close()

    break

except Exception, e:

    print e

Related questions

0 votes
1 answer

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...