How to securely copy data over SSH

Posted by

This is a really useful tip, and it has infinite uses in a *nix environment. You can pipe data over SSH, from both a client and a server, and process it on the other side. This is pretty useful as it avoids the requirement to have the hard disk space to store a file before it is imported. Here’s a few examples:

Copying a remote database to a local database

ssh user@server-domain.com 'mysqldump -u root --password=passwordhere remote-database-name-here | gzip -c' | gunzip | mysql -u root --password=passwordhere local-database-name-here
You’ll see  that we can pass a command as the 3rd parameter of ssh. This is executed on the remote end. Here, we take the output of mysqldump, gzip it and send it over SSH. We pipe the ssh command into gunzip to decompress it and finally pipe that into the local mysql command to import it.

 

Copying a folder of files to a remote server

cd /path/to/dir/to/copy;
tar -cz . | ssh user@server-domain.com 'tar -C /path/to/remote/dir -xzv'
In this example, we cd into a directory on the local machine, create a tar of its contents and pipe this over ssh into a reverse tar command on the remote server. The z flag on the tar commands gzips/ungzips the output for you, automagically. Note that this won’t include the root directory – i.e. it’ll transport  /path/to/dir/to/copy/* to  /path/to/remote/dir.

 

The two examples above have shown you using ssh on the left and right of the command. There’s plenty of other uses, see what you can do with it.

2 comments

  1. “ssh -C” automagically does gzip compression for you, makes the first command a little shorter.

Leave a Reply

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