How To: Setup SSH Keys Between Two Linux Machines
Connecting via SSH key is more secure than connecting via passwords. This is especially true if the only method you can SSH into a machine is via key. Connecting via SSH Key is also handy when you need to automate script connection without passwords. Here is how it is done:
Generating the SSH Key
Connect to each machine from the other machine via SSH (IE: ssh machine1.com, ssh machine2.com). This will create a .ssh directory in your home directory with the proper permissions. This directory may already be present.
On the machine you wish to connect to the other machine from (via SSH Key Authentication), generate a key by issuing this command:
ssh-keygen -t dsaYou will see:
Generating public/private dsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_dsa):Press enter to leave the path as default
You will see:Enter passphrase (empty for no passphrase):Enter a passphrase or press enter to leave it blank. If you want to connect to the remote machine without a password, leave this field blank. This is particularly useful in Linux scripts that need to be automatic (without password.
You will see:Enter same passphrase again:Enter the same passphrase again or press enter to leave it blank
Your key will be generated in the path you chose at step 2/3. You will also see some ASCII Art.
Transferring the SSH Key to the Remote Machine
Transferring the key to the remote machine is easy. You transfer the public key which was generated in step 6 above. Here is how:
Execute this command:
scp ~/.ssh/id_dsa.pub [username]@[host.com]:.ssh/authorized_keys2Enter the password of the user on the remote host.
That’s it. You should now be able to connect from the primary machine (from step 2 in the first section) using your SSH key. If you left the passphrase blank you will be able to connect without having to enter a password. Test it by connecting via SSH from the primary machine:
2 Responses
8.4.2011
Thank you thank you thank you!
8.12.2011
I have been using SCP between some of my VMWare ESX hosts, but never really thought about setting up the SSH key scenario you described here. I definitely need to test this out as I frequently copy VM templates between hosts in different data centers.