Sometimes you need to automate file copying between Linux servers. For example, your shell script might need to copy the backup from time to time and you don’t want to provide the password in the clean text format. So what you can do about this?
The simplest way is to create a public/private RSA key pair. Then, you can distribute your public key to all servers where you need password-less access. And voila, it’s simple as that. For the record, I’m using Ubuntu 16.04 but this tutorial should be more or less the same with any other Linux or Unix based distribution including MacOS as well as different Ubuntu versions.
You need to create keys pair on the server which we need to copy file(s) from:
$ ssh-keygen -t rsa -b 2048
You could use a 1024-bit key as well but 2048-bit keys are becoming standard. Keygen tool will prompt you with a few questions if you want to change the default configuration but there’s no need to, so you can just skip by hitting Enter until the end.
Now you have your keys pair in the /root/.ssh directory. What’s next is to copy public key which is stored in the id_rsa.pub file. To do that you should log into the server where you want to store your backup (to copy files). Now copy the public key to ~/.ssh/authorized_keys file of the user you are going to use in your shell script with SCP. You need to keep in mind not to overwrite authorized_keys with the public key but to append the key, because you could have more than one public keys for each server you need password-less access. It’s a simple text file so you can use any editor you like or shell command like this:
$ echo "content-of-public-key-file" >> ~/.ssh/authorized_keys
Now you are able to access that server without the password with any SSH-based command.