Post

Terminal: Copy recursive directory from remote with SSH and TAR

Harianto van Insulinde

Cloning directories from a remote server can be tricky. Sometimes SCP won't be enough. So I find a way to do it correctly for my purpose.

bash
root@local-server:/my/destiny/directory# ssh username@remote-server "sudo -S tar --directory='/my/directory/i/want/to/copy' --exclude='directory/to/skip' --exclude='directory/to/skip2/log' -vczpf - ." | tar -vxzpf - -C /my/destiny/directory

Go to your terminal, and it might look like this

bash
username@local-server:~#

Go to your destination folder for example /var/www.

bash
username@local-server:~# cd /var/www

result would be

bash
username@local-server:/var/www#

Log yourself as root

bash
username@local-server:/var/www# sudo -s

and type your password and result would be

bash
root@local-server:/var/www#

I know that my remote the source I want to copy is also /var/www.
Make sure the source and destination folder do exist

Type the command

bash
root@local-server:/var/www# ssh username@remote-server "sudo -S tar -C /var/www --exclude='log' --exclude='vhosts/mysecretstash' -vczpf - ." | tar -vxzpf -

See you saw sudo -S with the capital 'S'. this flag is needed when you need to type your password in prompt

As result you'll see lines of paths that being copied to.

Bonus one line command

bash
sudo ssh username@remote-server "sudo -S tar -C /var/www --exclude='log' --exclude='vhosts/mysecretstash' -vczpf - ." | sudo tar -vxzpf - -C /var/www

Of course it's possible to remove --exclude='' flags