SSH Permission Denied (Publickey) Error in AWS EC2: Authorized Keys Modification
In this article, we will discuss the SSH Permission Denied (Publickey) error that occurs when trying to SSH into an AWS EC2 instance. Specifically, we will cover the modification of authorized keys in the .ssh directory to resolve this issue.
Background
When launching an EC2 instance, a key pair is created to enable secure access to the instance via SSH. The private key is used to authenticate the client, while the public key is added to the authorized\_keys file on the EC2 instance. However, there are instances where this authentication fails, resulting in the SSH Permission Denied (Publickey) error.
Resolving the SSH Permission Denied (Publickey) Error
To resolve this error, we need to modify the authorized\_keys file on the EC2 instance. This can be done using the following steps:
- Connect to the EC2 instance using a terminal or SSH client.
- Navigate to the .ssh directory using the command
cd ~/.ssh. - Check if the authorized\_keys file exists using the command
ls -l. - If the file exists, check if the public key is present in the file. If not, add the public key to the file using the command
echo "public key" >> authorized\_keys. - If the file does not exist, create a new file using the command
touch authorized\_keysand add the public key to the file. - Ensure that the .ssh directory and the authorized\_keys file have the correct permissions. The .ssh directory should have a permission of 700, while the authorized\_keys file should have a permission of 600. This can be done using the commands
chmod 700 ~/.sshandchmod 600 ~/.ssh/authorized\_keys.
Preventing the SSH Permission Denied (Publickey) Error
To prevent the SSH Permission Denied (Publickey) error from occurring, it is recommended to:
- Create a new key pair when launching a new EC2 instance.
- Ensure that the private key is kept secure and not shared with anyone.
- Regularly backup the authorized\_keys file to prevent data loss.
- Set the correct permissions for the .ssh directory and authorized\_keys file.
The SSH Permission Denied (Publickey) error in AWS EC2 can be resolved by modifying the authorized\_keys file in the .ssh directory. By following the steps outlined in this article, users can regain access to their EC2 instance. Additionally, taking preventive measures such as creating new key pairs, securing the private key, and setting the correct permissions can help prevent this error from occurring in the future.