Login to server using SSH key
To log in to a server using an SSH key, you first need an SSH key pair. You can learn how to generate SSH keys in the following article:
You can log in using the ssh command by providing the username and the host name in the following format:
ssh [email protected]
SSH login with private key without password
Logging in with an SSH key means you don’t have to type your password anymore. The only time you will be prompted for a password is when your private key is protected with a passphrase – in that case, you enter the passphrase locally to decrypt the key (this is not the server password).
When you have more than one SSH key
Sometimes you work with multiple servers and each one uses a different SSH key. In that case, you can explicitly specify which private key you want to use. If your server uses a port other than 22, you must also specify that port:
ssh -p 234 -i ~/.ssh/myKeyName-ed25519 [email protected]
The -i (identity file) argument tells the SSH client which file to use for authentication. The -p argument specifies the port that should be used for logging in.
WARNING! If you have a large number of different SSH keys (for example, more than 5–6), attempting to log in using the command above may result in an error:
Too many authentication failures
This happens because the specified key is only one of the keys used during the login attempt. In practice, the SSH client sends all available SSH keys to the server until it finds a matching one. To solve this problem and prevent other keys from being sent, use the following command:
ssh -o IdentitiesOnly=yes -p 234 -i ~/.ssh/myKeyName-ed25519 [email protected]
The -o IdentitiesOnly=yes option tells the SSH client not to use any other keys loaded in memory and to use only the specified key: ~/.ssh/myKeyName-ed25519.
Simplifying SSH login using the SSH config file
If you frequently log in to different servers, it can be difficult to remember multiple commands with different ports, SSH keys, or usernames. Instead, you can assign your own “label” to each connection and use it in place of the full command. Such shortcuts can be added to the ~/.ssh/config file, for example:
Host myserver
HostName example.pl
User username
Port 234
IdentityFile ~/.ssh/myKeyName-ed25519
IdentitiesOnly yes
With this solution, logging in is reduced to simply running the ssh command with the shortcut name:
ssh myserver
Setting up login configuration in the SSH config file also works well when you have a large number of different SSH keys, because it allows you to precisely specify which key should be used for authentication. More information about the config file can be found here: https://linuxize.com/post/using-the-ssh-config-file/