Getting a "Permission Denied (publickey)" error while trying to SSH with a key

Getting a "Permission Denied (publickey)" error while trying to SSH with a key

If you see a "Permission denied (publickey)" error when trying to SSH using a key, here are some common problems to look for:

  1. Check Key Permissions: Make sure your private key file has secure permissions. Set the permissions to 600.

     chmod 600 /path/to/private-key.pem
    
  2. Check Key Format: Be sure your private key has the right format. SSH keys usually use OpenSSH format. If your key was made with a different tool, you might need to change it. To change a PuTTY private key (.ppk) to OpenSSH format, use this command:

     puttygen private-key.ppk -O private-openssh -o private-key.pem
    
  3. Check SSH Agent: If you're using an SSH agent to manage your keys, ensure that the key is added to the agent using the ssh-add command:

     ssh-add /path/to/private-key.pem
    
  4. Check Authorized Keys on Server: Make sure your public key is in the ~/.ssh/authorized_keys file on the remote server. You can add it yourself or use the ssh-copy-id command:

     ssh-copy-id -i /path/to/public-key.pub username@remote-server-ip
    

    Replace /path/to/public-key.pub with the path to your public key file.

  5. Check Server Configuration: Be sure the SSH server on the remote computer is set up to allow key-based authentication. Look at the sshd_config file on the server:

     sudo nano /etc/ssh/sshd_config
    

    Ensure that the following lines are present and not commented out:

     PubkeyAuthentication yes
     AuthorizedKeysFile  .ssh/authorized_keys
    

    Restart the SSH service after making changes:

     sudo service ssh restart
    
  6. Check User Home Directory Permissions:Make sure the user's home directory on the remote server has the right permissions. It shouldn't be writable by the group or everyone:

     chmod 700 /home/username
    

After following these steps, try connecting again. If you still have problems, using the verbose mode (-v option) can give more information about the authentication process:

ssh -v -i /path/to/private-key.pem username@remote-server-ip

Check the output for any error messages that could help you find the issue.