Terminal: Copy recursive directory from remote with SSH and TAR

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.

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

username@local-server:~#

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

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

result would be

username@local-server:/var/www#

Log yourself as root

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

and type your password and result would be

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

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

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