Having to type in passwords manually all day long into servers you manage is a pain. You should be using ssh keys, they’re more secure, and you don’t have to remember your passwords. Below at the steps to generate and use ssh keys for all your servers.
Step 1) Generate SSH Keys
This should be run locally, on your client, wherever you run ssh to connect to the remote servers. You can do this on the server as well and copy (and remove) the private key file locally if you’re running windows too.
ssh-keygen -t rsa
Output:
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
It immediately asks you for a file path, I entered “/root/.ssh/id_rsa_test” but you might want to name it something different. Possibly something like id_rsa_server_name.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_test
It will then asks you for a passphrase, I didn’t provide one, you can if you want it to be more secure. It’s highly recommended by security experts to use a passphrase.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa_test.
Your public key has been saved in /root/.ssh/id_rsa_test.pub.
The key fingerprint is:
5e:2b:89:85:7b:83:f2:86:51:f3:5a:e9:7a:26:d3:57 root@mike-dev
The key’s randomart image is:
+–[ RSA 2048]—-+
| |
| |
| |
| o. |
| ..oS.. |
| . *+o .E |
| .o+=* .. |
| .o=.=o. |
| .o* . |
+—————–+
You now have generated both files as below.
public key: /root/.ssh/id_rsa_test.pub
private key: /root/.ssh/id_rsa_test
The public key goes on the server, the private key stays on your desktop, or wherever your ssh client will be.
Step 2) Save Public Key on Server
ssh-copy-id -i ~/.ssh/id_rsa_test.pub [email protected]
If this gives you an issue or it says “WARNING: All keys were skipped because they already exist on the remote system.”, thats a known ssh bug you can just open ~/.ssh/authorized_keys and copy and paste it into the file manually youself. Or you can also run this command manually as below.
Copy It Manually to the server “authorized_keys” file.
cat ~/.ssh/id_rsa_test.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
If you get a permissions problem you prob need to set your local and remote key permissions. Most likely this will be best.
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
Step 3) Test SSH Access
You can now test your key and it should let you right in, passing your private key to the ssh command.
ssh -i ~/.ssh/id_rsa_test [email protected]
Step 4) Setup Local Client SSH
If you’d like to not have to remember which servers are using which keys you can set it up in your local ssh clients config located at ~/.ssh/.config. This will allow you to login with only a “ssh yourserver.com”
Host yourserver.com IdentityFile ~/.ssh/id_rsa_test User yourUsername