TL;DR
Yes, you can initiate an SSH session using a public key instead of a password. This is more secure and convenient. Here’s how to set it up.
Setting Up SSH Public Key Authentication
- Generate an SSH Key Pair: If you don’t already have one, create a new SSH key pair on your local machine (the computer you are connecting *from*). Open your terminal and run:
ssh-keygen -t rsa -b 4096You’ll be prompted for a file to save the key. The default (~/.ssh/id_rsa) is usually fine. You can also set a passphrase for extra security (recommended).
- Copy Your Public Key to the Server: There are several ways to do this.
- Using
ssh-copy-id(easiest): If you have password access to the server, use:ssh-copy-id user@server_ip_addressYou’ll be prompted for the server’s password.
- Manually Copying (if
ssh-copy-idisn’t available):- Display your public key:
cat ~/.ssh/id_rsa.pub - Copy the entire output of this command.
- Connect to the server using password authentication (e.g.,
ssh user@server_ip_address). - Edit the
~/.ssh/authorized_keysfile on the *server*.nano ~/.ssh/authorized_keys - Paste your public key into this file on a new line. Save and close the file. If the .ssh directory or authorized_keys file doesn’t exist, create them:
-
mkdir -p ~/.ssh -
chmod 700 ~/.ssh -
touch ~/.ssh/authorized_keys -
chmod 600 ~/.ssh/authorized_keys
-
- Display your public key:
- Using
- Test the Connection: Try connecting to the server again:
ssh user@server_ip_addressIf everything is set up correctly, you should be logged in without being prompted for a password. If it still asks for a password, see the troubleshooting section below.
Troubleshooting
- Permissions: Make sure the
~/.sshdirectory has permissions of 700 (drwx——) and the~/.ssh/authorized_keysfile has permissions of 600 (-rw——-). - Correct Public Key: Double-check that you copied the *public* key (id_rsa.pub), not the private key (id_rsa).
- Authorized Keys File: Ensure your public key is on a single line in the authorized_keys file, with no extra characters or spaces.
- SSH Server Configuration: Verify that the SSH server configuration allows public key authentication.
- Edit
/etc/ssh/sshd_config(you’ll need root privileges). - Make sure these lines are set to ‘yes’:
PubkeyAuthentication yesAuthorizedKeysFile .ssh/authorized_keys
- Restart the SSH service:
sudo systemctl restart sshd
- Edit
- SELinux/Firewall: Check if SELinux or a firewall is blocking SSH access.