SSH-ing into EC2 using Lambda Function (Authentication failed, Authentication Error)

0

I am attempting to SSH into an EC2 instance through a Lambda function using the Paramiko library. Despite double-checking the key file, username, security group permissions, and ensuring that everything is in order, I am still encountering an Authentication Error.

import json
import boto3
import paramiko

def lambda_handler(event, context):
    # boto3 client
    client = boto3.client("ec2")

    # getting instance information
    describeInstance = client.describe_instances()

    hostPublicIP = []
    # fetchin public IP address of the running instances
    for i in describeInstance["Reservations"]:
        for instance in i["Instances"]:
            if instance["State"]["Name"] == "running":
                hostPublicIP.append(instance["PublicIpAddress"])

    print("Active EC2 instance IP: ",hostPublicIP)
   
    key = paramiko.RSAKey.from_private_key_file('EC2-Key.pem')
    print("RSA Key: ", key)
    
    host = hostPublicIP[0]
    print("Connecting to : " + host)
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    ssh_client.connect(hostname=host, username="ec2-user", pkey=key)
    print("Connected to: " + host)

    return {"statusCode": 200, "body": json.dumps("Thanks!")}

Error:


Response
{
  "errorMessage": "Authentication failed.",
  "errorType": "AuthenticationException",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 40, in lambda_handler\n    ssh_client.connect(hostname=host, username=\"ec2-user\", pkey=key)\n",
    "  File \"/opt/python/lib/python3.8/site-packages/paramiko/client.py\", line 435, in connect\n    self._auth(\n",
    "  File \"/opt/python/lib/python3.8/site-packages/paramiko/client.py\", line 764, in _auth\n    raise saved_exception\n",
    "  File \"/opt/python/lib/python3.8/site-packages/paramiko/client.py\", line 664, in _auth\n    self._transport.auth_publickey(username, pkey)\n",
    "  File \"/opt/python/lib/python3.8/site-packages/paramiko/transport.py\", line 1580, in auth_publickey\n    return self.auth_handler.wait_for_response(my_event)\n",
    "  File \"/opt/python/lib/python3.8/site-packages/paramiko/auth_handler.py\", line 250, in wait_for_response\n    raise e\n"
  ]
}

已提问 9 个月前577 查看次数
3 回答
1

Hi,

You code looks good.

But, since your message is ""Authentication failed.", did you validate via EC2 Instance Connect that the same key allows you to access the EC2 instance? This will clear potential key-related issues.

Also, I would suggest to activate paramiko's logging at DEBUG level to better see what's happening when connection is initiated: you may have a routing and sec group issue between your Lambda and your EC2.

Best,

Didier

profile pictureAWS
专家
已回答 9 个月前
  • It works fine when running locally but run through lambda function it gives me this error

0
已接受的回答

I resolved the issue. The problem was related to the versioning of the paramiko library and its dependencies. The code started working after I updated the libraries to the following versions:

  • paramiko==2.9.1
  • cryptography==2.7.0
  • bcrypt==3.1.7

(Python: 3.8)

已回答 9 个月前
profile picture
专家
已审核 2 个月前
0

Did you open SSH to the world in the Security Group? I highly recommend you not do this. Rather, connect the Lambda to the VPC and only allow private IPs to SSH in the SG.

profile pictureAWS
专家
iBehr
已回答 9 个月前
  • Thank you for your recommendation. I have started working on it. However, I am facing an issue. Without connecting the lambda function to the VPC, the code works fine and I am able to SSH into the EC2 instance. But when I connect the lambda function to the VPC, I get a timeout error.

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则