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:
- SSM Run Manager
- Expose an API on the EC2 instance and call that API
If you really want to do this, perhaps for some academic reason, then:
- store the keypair in Secrets Manager and give the Lambda permission to read it
- 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.