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])

Monday 29 April 2019

How to install django on Windows?

1. Download get-pip.py from pip official download site
    https://bootstrap.pypa.io/get-pip.py

2. Run pip installation using command "python get-pip.py"


3. Install django by running below command "pip install django"









4. installation is successful, check django version to confirm installation using below command.
    python -m django --version

5. Create your first project using below command. It will create project folder with name "mysite" under given location.

    django-admin startproject mysite