Managing remote systems is a time consuming endeavour. Aside from just standard maintance, other things are required to be an effective System Administrator. One of those is secure system access. It wouldn’t be good for you (or your client) if your System Admin password was suddenly common knowledge. Just like everyone else, System Admins tend to select easy to remember, short passwords.
Fortunately, there is a solution. When connecting two Linux machines together – whether its because an administrator is connecting to a remote system, or you are doing a remote back up (you do store data off site, right?) – the ability to automatically connect to another machine is a huge time saver.
To begin let me make clear that this is not the only way to accomplish this task. This works for what I have done. Additionally, since I have the requirement of needing to automate these logins between servers I do not enable the passphrase option of using SSH keys. This is a noted, and in my case, accepted security risk. I mitigrate this security risk by limiting what the backup user is able to do on either system. Linux permissions is a broad topic and outside of the scope of this tutorial.
For this tutorial there will be two machines needed: LocalMachine and RemoteMachine.
On LocalMachine enter the following:
ssh-keygen -t rsa -f ~/.ssh/Key_4_RemoteMachine
At each of the prompts this command generates, hit enter. Do not fill in a passphrase or you (and your automated scripts) will be required to enter this passphrase when connecting to a remote system.
This generates a public/private RSA key pair and gives the files the appropriate permissions. These files are stored in the .ssh folder in the current user’s home directory. They are named Key_4_RemoteMachine and Key_4_RemoteMachine.pub. The first one is your private key – do NOT give this to anyone. The second is the public key – anyone in the world can have this. You can change the file name generated by modifying the argument passed after the -f switch.
We now need to get this public file to the RemoteMachine. We do that by running the following command:
ssh-copy-id -i ~/.ssh/Key_4_RemoteMachine.pub <user>@RemoteMachine
<user> is the username that will be logged into automatically. When you enter this command, you will be required to input <user>‘s password so that the key can be transferred.
At this point you can log into the <user> account on RemoteMachine without a password. To use this key in a script (ie. Backup script) you first need to move the Private Key to a location that your script can access. Using the example above, if you have a script that runs from the user that created the keys you will have no issues. The command to automatically log in is:
ssh -i ~/.ssh/Key_4_RemoteMachine <user>@RemoteMachine
Notice that you are now specifying the private key.