To establish an SSH connection between your PC and Raspberry Pi 4 running Ubuntu, you may encounter a "Permission denied (publickey)" error when using client-side public key authentication. This article will guide you on how to resolve this issue by manually adding the authorized_keys file on your Raspberry Pi.
Prerequisites:
- SSH client installed on your PC (e.g., PuTTY, OpenSSH)
- SSH server installed and running on your Raspberry Pi (SSH is enabled by default on Ubuntu)
Step 1: Retrieve the client's public key
On your PC, locate the public key file (id_rsa.pub or id_ed25519.pub) in the .ssh directory of your user account.
$ cd ~/.ssh
$ cat id_rsa.pub
Step 2: Connect to your Raspberry Pi via SSH
Connect to your Raspberry Pi using SSH. If you haven't set up password authentication, you'll need to use a key-based authentication method.
$ ssh pi@raspberrypi
Replace pi with your Raspberry Pi's default username (ubuntu for Ubuntu) and raspberrypi with your Raspberry Pi's IP address.
Step 3: Create the authorized_keys file
Once connected, create the authorized_keys file in the .ssh directory on your Raspberry Pi.
$ sudo mkdir -p ~/.ssh
$ sudo touch ~/.ssh/authorized_keys
$ sudo chmod 600 ~/.ssh/authorized_keys
Step 4: Add the public key to the authorized_keys file
Copy the public key content from your PC and paste it into the authorized_keys file on your Raspberry Pi.
$ cat id_rsa.pub | sudo tee -a ~/.ssh/authorized_keys
Step 5: Test the SSH connection
Exit the SSH session on your Raspberry Pi and try to connect again from your PC. You should now be able to log in without encountering the "Permission denied (publickey)" error.
$ exit
$ ssh pi@raspberrypi
Summary:
- Retrieve the client's public key.
- Connect to your Raspberry Pi via SSH.
- Create the
authorized_keysfile and set its permissions. - Add the public key to the
authorized_keysfile. - Test the SSH connection.
References: