SSH key-based authentication is a secure way to connect to remote servers without entering a password. In this tutorial, we will guide you through the process of setting up SSH key-based authentication.
Generating SSH Keys
To start using SSH key-based authentication, you need to generate a pair of SSH keys: a private key and a public key. You can generate these keys using the ssh-keygen
command on your local machine.
ssh-keygen
By default, this will create two files in your ~/.ssh/
directory: id_rsa
(private key) and id_rsa.pub
(public key). If you want to specify a different name for your keys, you can provide it as an argument:
ssh-keygen -t rsa -b 4096 -f my_key
This will create two files: my_key
(private key) and my_key.pub
(public key).
Copying the Public Key to the Remote Server
Once you have generated your SSH keys, you need to copy the public key to the remote server. You can use the ssh-copy-id
command for this:
ssh-copy-id user@host
Replace user
with your username on the remote server and host
with the hostname or IP address of the remote server.
If you have specified a different name for your keys, you need to provide the path to the public key file as an argument:
ssh-copy-id -i ~/.ssh/my_key.pub user@host
Configuring the Remote Server
After copying the public key to the remote server, you need to configure the SSH server to use key-based authentication. You can do this by editing the sshd_config
file on the remote server:
sudo nano /etc/ssh/sshd_config
Make sure that the following lines are uncommented and set to yes
:
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile %h/.ssh/authorized_keys
Also, make sure that password authentication is disabled by setting passwordAuthentication
to no
:
PasswordAuthentication no
Setting Permissions
To ensure that the SSH server can read the authorized keys file, you need to set the correct permissions on the ~/.ssh/
directory and the authorized_keys
file:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
You should also make sure that your home directory is not writable by others:
chmod g-w,o-w ~
Testing Key-Based Authentication
After configuring key-based authentication, you can test it by trying to connect to the remote server using SSH:
ssh user@host
If everything is set up correctly, you should be able to log in without entering a password.
Troubleshooting
If you encounter issues with key-based authentication, here are some common problems to check:
- Make sure that the public key is correctly copied to the remote server.
- Verify that the
sshd_config
file is correctly configured and that theauthorized_keys
file is readable by the SSH server. - Check that the permissions on the
~/.ssh/
directory and theauthorized_keys
file are correct. - Ensure that your home directory is not writable by others.
By following these steps, you should be able to set up SSH key-based authentication and securely connect to remote servers without entering a password.