February 8, 2023
Python script to check state of EC2 instances
In this blog, we will write a Python script to check the state of EC2 instances in a region and if an instance is in a running state then get its uptime. In this script, we will use the Boto3 and Paramiko modules.
Boto3 is an AWS Software Development Kit for Python using which we use various AWS services like EC2 and S3.
To install the boto3 module use the following command:
pip3 install boto3
The Paramiko module helps us to establish SSH connections with servers. Paramiko is an implementation of the SSHv2 protocol.
To install the paramiko module use the following command:
The following script can be broken down into the following steps:
- Connecting to AWS using boto3 client.
- Listing instances and their state using boto3 describe_instances resource. The script will ask the user to enter the region name and will list elastic cloud compute instances in that region.
- Using the paramiko module to SSH to the instance which is running.
- Run the following command to get uptime. The uptime command in Linux is used to find out how long the system is active or running.
uptime -p
import boto3
import paramiko
try:
region=input("Enter region name: \n")
print("\n")
ec2_client=boto3.client('ec2',region_name=region)
response=ec2_client.describe_instances()
for instances in response['Reservations']:
for each in instances['Instances']:
if each['State']['Name'] == "running":
for x in each['NetworkInterfaces']:
i= (x['Association']['PublicIp'])
key = paramiko.RSAKey.from_private_key_file("/home/vagrant/scripts/dell-ohio-keypair.pem")
print(f"\nInstanceId: {each['InstanceId']}, State:{each['State']['Name']}")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname= i, username='ubuntu', pkey=key)
cmd = "uptime -p"
stdin, stdout, stderr = client.exec_command(cmd)
stdout = stdout.readlines()
for line in stdout:
print("The uptime of the instance is:")
print(line)
client.close()
elif each['State']['Name'] != "running":
print(f"InstanceId: {each['InstanceId']}, State:{each['State']['Name']}\n")
except Exception as e:
print (e)
Please contact our technical consultants if you have anything related to cloud infrastructure to be discussed.