Wednesday 16 October 2019

Execute commands remotely on AWS EC2 linux instance in Python

import paramiko

##Initiate SSH Connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=<hostIp>,port=<port>,username=<username>,key_filename=<keypath>)
print("Connection Successfully Established!")
except paramiko.AuthenticationException:
print("Authentication Failed!")

#Execute Commands
ssh.exec_command("ls -lst")

Remote connection to AWS EC2 Linux Instance in Python

import paramiko

##Initiate SSH Connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=<host_ip>,port=<port>,username<username>,key_filename=<keypath>)
print("Connection Successfully Established!")
except paramiko.AuthenticationException:
print("Authentication Failed!")

Logging module in python

import logging

##Logging Basic Configurations
logging.basicConfig(filename="Scriptlog.log" , format='%(asctime)s %(message)s', filemode='w')
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO) #Log Level can be changed to DEBUG, ERROR, WARNING etc.

##Put below logger where you want logging
logger.info("Python script has been completed")


Python Code to Stop AWS EC2 Instances Using Filters


import sys
import boto3
from botocore.exceptions import ClientError

region = 'xx-east-x'

InstanceList = []

try:
        ec2 = boto3.client('ec2', region_name=region)
except Exception as e:
        print(e)
        sys.exit(1)

response = ec2.describe_instances(
        Filters=[{
'Name': '<tagname>',
'Values': ['<value>']
},
                {
                        'Name' : 'instance-state-name',
                        'Values' : ['stopped']
                }]
)
#print (response)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
InstanceList.append(instance['InstanceId'])

#print InstanceList
for instanceid in InstanceList:
startec2 = ec2.start_instances(InstanceIds=[instanceid])

Python Code to Start AWS EC2 Instances Using Filters


import sys
import boto3
from botocore.exceptions import ClientError

region = 'xx-east-x'

InstanceList = []

try:
        ec2 = boto3.client('ec2', region_name=region)
except Exception as e:
        print(e)
        sys.exit(1)

response = ec2.describe_instances(
        Filters=[{
'Name': '<tagname>',
'Values': ['<value>']
},
                {
                        'Name' : 'instance-state-name',
                        'Values' : ['stopped']
                }]
)
#print (response)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
InstanceList.append(instance['InstanceId'])

#print InstanceList
for instanceid in InstanceList:
startec2 = ec2.start_instances(InstanceIds=[instanceid])