SSH Extras
How to setup SSH Key Authentication
Section titled “How to setup SSH Key Authentication”To enable SSH key authentication in Linux, you need to generate a public authentication key and append it to the remote host’s ~/.ssh/authorized_keys file.
The following steps describe the process for configuring key authentication login:
-
Check for an existing SSH key pair.
Before generating a new SSH key pair, first check if you already have an SSH key on your client machine, because you don’t want to overwrite your existing keys.
Run the following
lscommand to see if existing SSH keys are present:Terminal window ls -al ~/.ssh/*.pubIf there are existing keys, you can either use those and skip the next step or generate a new one.
If you see
No such file or directoryorno matches found, it means that you do not have an SSH key and you can proceed with the next step and generate a new one. -
Generate a new SSH key pair.
The following command will generate a new 4096-bit SSH key pair with your email address as a comment:
Terminal window ssh-keygen -t ed25519 -b 4096 -C "your_email@domain.com"Press Enter to accept the default file location and file name, or append the
-fflag to set a custom name, for example:Terminal window ssh-keygen -t ed25519 -b 4096 -C "your_email@domain.com" -f ~/.ssh/my_ed25519_keyNext, the
ssh-keygentool will ask you to type a secure passphrase. Whether you want to use a passphrase is up to you, but we highly recommend you set a strong passphrase. If you don’t want to use a passphrase, just press Enter.To be sure that the SSH keys are generated, you can list your new private and public keys with:
Terminal window ls ~/.ssh/id_* -
Copy the public key.
Now that you have generated an SSH key pair, in order to be able to log in to your server you need to copy the public key to the server you want to manage.
The easiest way to copy your public key to your server is to use a command called
ssh-copy-id. On your local machine terminal, type:Terminal window ssh-copy-id remote_username@server_ip_addressYou will be prompted to enter the
remote_usernamepassword. Once the user is authenticated, the public key will be appended to the remote user’sauthorized_keysfile and the connection will be closed.If for some reason the
ssh-copy-idutility is not available on your local computer, you can use the following command to copy the public key:Terminal window cat ~/.ssh/id_rsa.pub | ssh remote_username@server_ip_address "mkdir ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys" -
Log in to your server using SSH keys.
After completing the steps above, you should be able to log in to the remote server. To test it, just try to log in to your server via SSH:
Terminal window ssh -i ~/.ssh/id_ed25519.pub remote_username@server_ip_addressIf everything went well, you will be logged in after entering your passphrase.