SCP is a powerful utility that allows us to securely copy files between remote machines. What makes it even more powerful is the ability to add it to scripts and so for today’s quick tutorial I will walk you through how you can go about either copying files from or to a remote machine with the use of SCP.

Now normally when you copy files with SCP you will be prompted for the remote machine’s password in order to continue with the copy operation. However, obviously if we wish to script with SCP we will need to get around this restriction and so we take a quick dive into the of public key cryptography.

Basically what we are going to do now is generate a public/private key pair for your local machine which is going to run the SCP function and then hand out the public to the remote machine so that the two of them can communicate quite happily with one another.

To generate the key pair, enter:

ssh-keygen -t rsa

The machine will ask you to enter a file name in which to save the generated key – just hitting enter will force it to create the key file in its default spot. It will then ask for a passphrase, which you can happily skip by just pressing enter twice.

The system will then spit out its report and reveal to you the location where it saved the key file (which always ends .pub by the way)

You then need to put the generated key data into the ~/.ssh/authorized_keys file of the user which you will be ‘logging in’ as on the remote machine.

A simple way to do this is to use the ssh-copy-id function. Simply call:

ssh-copy-id -i ~/.ssh/id_rsa.pub username@host

Once done, you can test this by ssh’ing into the remote machine and checking the existence of the ~/.ssh/authorized_keys file.

Okay, and now we are ready for the actual SCP file copy bit!

To copy files to a remote machine, simply use:

scp -v /myfilestocopy username@host:/directorytosave

Alternatively, to pull down files from a remote machine, use:

scp -v username@host:/myfilestocopy /directorytosave

Note that the -v switch isn’t necessary – I just like seeing on the screen that something is actually happening!

And there you go, as simple as that. Nifty.

Related Link: http://www.howtogeek.com/