The simplest way to programmatically SSH into an EC2 instance is to using the Paramiko package. In this post, I will show you how to use this package to SSH with multiple retries and then execute your commands on it.
We will be using python for our code so make sure that you have
boto3 library installed.
pip install boto3
Next, you will need to configure the credentials. Please follow the docs for the configuration steps.
SSH into EC2 using Boto3
Get your instances
Firstly, we will use
boto3 to get the instance that we want to SSH into. The following code snippets give us the ip_address of the EC2 instance.
Install Paramiko using Pip. If you are having trouble installing the package, refer to their installation guide.
pip install paramiko
First, create an instance of Paramiko SSH client:
ssh = paramiko.SSHClient()
SSH with retries
Use the following method to SSH with retries. While using the library I noticed that out if you try SSHing into the instance just after the instance is started, it sometimes fails. So I have added a simple recursive retrial logic that tries connecting thrice after an interval of 5 seconds each.
Call this method to SSH into the instance:
ssh_connect_with_retry(ssh, ip_address, 0)
Note: You can also get the public IP of your EC2 instance from the AWS dashboard.
Run your commands
Once you have connected to your instance, you can run your commands and get back the std output:
stdin, stdout, stderr = ssh.exec_command("echo 'Hello World!'")
Note: If you are trying to run multiple commands at once, you can probably read all the commands from a text file and to make it easily manageable.
Putting it all together
Here’s the complete code snippet: