If you are connecting via SSH to multiple servers more often, it might be really annoying to enter you password everytime you want to connect to the server. Public key authentication is the right way to avoid remembering all the passwords and except of comfort it offers also much higher security level.
You can use public key authentication in two ways. You can generate key pairs without any password protection and for connection you just need to have your key on current computer, or you can use encrypted keys protected with one master password. It is possible to connect to multiple servers using one key pair, so you need to remember and enter everytime the same password. Let’s have a look how to achieve it.
Generating key pair
# ssh-keygen -t rsa
If you want to encrypt your key with passphrase, type it or leave blank for no passphrase.
Handling multiple keys
What if you have to use more keys e.g. one for work and other one for you private servers? You can specify the file name even with additional comment:
# ssh-keygen -t rsa -f ~/.ssh/id_rsa.private -C "private servers"
But now your client does not know what key is for what server. One way is to try all keys for every connection. Execute for every key;
# echo "IdentityFile ~/.ssh/id_rsa.private" >> ~/.ssh/config
Of course, more elegant way is to filter keys by hostname directly in this config file, so open it and try to type something like this:
You can see that in config file you can specify even more than just your key file.
Pushing onto server
Last step is to push generated keys onto remote server.
# cat .ssh/id_rsa.pub | ssh example.com "mkdir -p .ssh && chmod 0700 .ssh && cat >> .ssh/authorized_keys"
This complicated command will connect to the server and execute given command which adds your public key to accepted keys list. Here are some parts of this command you should be aware of:
- .ssh/id_rsa.pub – your public key, use the correct file name
- mkdir -p .ssh – creates .ssh dir if it does not exist
- cat >> .ssh/authorized_keys – note that >> sign, it appends your key, so you can use multiple keys for one server
If you are using the same username on the server and host machine, from now you can connect with just one short command.
# ssh myserver.com
And that’s it, pretty simple, huh?