How to copy file with SCP from one server to other without password

Sometimes we will need to automate file copying between our servers. For example, our shell script might need to copy the backup from time to time and we don’t want to provide the password in the clean text format. So what we can do about this?

The simplest way is to create a public/private RSA key pair. Then, we can distribute our public key to all servers where we need passwordless 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.

We are going to create keys pair on the server from which we need to copy file(s):

$ ssh-keygen -t rsa -b 2048

We could use a 1024-bit key as well but 2048-bit keys are becoming standard. Keygen tool will prompt us with a few questions if we want to change the default configuration but there’s no need to, so we will just keep hitting Enter until the end.

Now we 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 we will log into the server where we want to store our backup (to copy files). Let’s copy the public key to ~/.ssh/authorized_keys file of the user we are going to use in our shell script with SCP. We need to keep in mind not to overwrite authorized_keys but with the public key but to append the key, because we could have more than one public keys for each server we need passwordless access. It’s a simple text file so we can use any editor we like or something like this:

$ echo "content-of-public-key-file" >> ~/.ssh/authorized_keys

Now we are able to access that server without the password with any SSH-based command.

Leave a Reply

Your email address will not be published. Required fields are marked *