1
votes

I'm trying to write my first Python code in Lambda function that will check whether i'm able to SSH (port 22) in to an EC2 instance.

I have created an EC2 instance with Security Group 22 CidrIP my public IP then, created a Lambda function with python 3.8 as runtime in the same account

Now, through code i,m trying to SSH into EC2 by passing EC2 Public IP, Username, Key pair

and execute one command, example: sudo su

Question:

  1. Where should i place my keypair?
  2. What is the code to SSH in to EC2 from lambda funtion?
1
Thanks for sharing this. This is Node.JS ;How do i find the equivalent python code. - Nikhil K Murali
WHY do you wish to write this Lambda function? What is the actual goal you are wanting to achieve by doing this? - John Rotenstein
Hi John, we need to validate all the services that are created in my project is getting created. we are creating 2 EC2 one is a webserver and another is application server. webserver code is completed and now in application server we need to make sure the security groups are correct(22 port) and we are able to SSH into machine. I'm not able to check the SSH part. and the whole validation code needs to be done through AWS Lambda function. thank you. - Nikhil K Murali

1 Answers

6
votes

The first thing I would say is that you should almost never SSH from Lambda into EC2. There are much better ways to remotely run scripts on EC2, including:

  1. SSM Run Manager
  2. Expose an API on the EC2 instance and call that API

If you really want to do this, perhaps for some academic reason, then:

  1. store the keypair in Secrets Manager and give the Lambda permission to read it
  2. use a Python package such as Fabric or Paramiko

[Update: it seems that you're trying to validate that SSH access is blocked]

The best way to validate security groups is to use the EC2 API, describe the instance(s), enumerate the security groups and their inbound rules. If you don't trust that approach then you could try to SSH to the instance using the method I proposed above (though you only need to try to connect for the test to be useful, presumably).

The problem you're going to have is that the security groups could potentially have been set up to block all SSH access (which is the default, by the way) with the exception of a single 'attacker' IP address which is allowed. Your Lambda SSH connection attempt will fail, because it's not coming from that one 'attacker' IP, yet your Lambda test will report "I cannot access the web server over SSH, test is successful". That's an invalid test.