Updated on 30 Mar 2020
Here are a couple of external references for scp
Copy a file from local to remote machine
scp <FILENAME> username@to_host:<DESTINATION>
Copy a directory from local to remote machine
scp -r /directory/ username@to_host:/directory/
Copy a file from remote to local machine
scp username@from_host:/directory/file.txt /local/directory/
Copy a directory from remote to local machine
scp -r username@from_host:/remote/directory/ /local/directory/
- -r means to recursivily copy all files and sub-folders.
SCP command - with SSH key
Inorder for scp to work with ssh (using an identity file), you must first create an ssh key on your client machine and share that with the server. We can follow the instructions on how to set that with my other article ssh-keys. Just remember you will need the same username on both machines, and the account (on the other machine) must be set up so you can login.
scp -i ~/.ssh/id_rsa <FILENAME> USER@SERVER:<DESTINATION>
- -i is the identity file
So what this is doing is it is attempting to login to the server, with the given user and using the ssh key provided. Remember, a linux user can only have one ssh key.
Example from Adlib tools deployment
Here is an example of how I have done it in adlib-tools deployment with Jenkins. In this particular case, I am overwriting the base files that were copied with rsync with a production specific file.
YII_SERVER=jenkins@remote_server:/var/www/yii/adlib-tools scp -i ~/.ssh/id_rsa $WORKSPACE/deploy/assets/prod/config/console.php $YII_SERVER/config/
Setting up the SSH key
We can use SCP with ssh keys to provide authentication. This is very useful when you have automated shell scripts that interact with a remote machine and you can’t be dealing with usernames and passwords. My notes on ssh-keys show how this can be done.