How To Use tar Command Through Network Over SSH Session

Get real time updates directly on you device, subscribe now.

How do I use tar command over secure ssh session running on Linux or Unix-like system?

The GNU version of the tar archiving utility (and other old version of tar) can be use through network over ssh session. Do not use telnet command, it is insecure. You can use Unix/Linux pipes to create archives.

Let us see some examples of how to use the tar command over ssh securely to create archives on Linux or Unix-like system.


The syntax is as follows to ssh into box and run the tar command:
ssh [email protected] tar czf - /dir1/ > /destination/file.tar.g
ssh [email protected] 'cd /dir1/ && tar -cf - file | gzip -9' >file.tar.gz
The following command backups /wwwdata directory to (IP host over ssh session.
# tar zcvf - /wwwdata | ssh [email protected] "cat > /backup/wwwdata.tar.gz"OR# tar zcvf - /wwwdata | ssh [email protected] "cat > /backup/wwwdata.tar.gz"
Sample outputs:

tar: Removing leading `/' from member names

The default first SCSI tape drive under Linux is /dev/st0. You can read more about tape drives naming convention used under Linux here. You can also use dd command for clarity purpose:
# tar cvzf - /wwwdata | ssh [email protected] "dd of=/backup/wwwdata.tar.gz"
It is also possible to dump backup to remote tape device:
# tar cvzf - /wwwdata | ssh [email protected] "cat > /dev/nst0"
OR you can use mt to rewind tape and then dump it using cat command:
# tar cvzf - /wwwdata | ssh [email protected] $(mt -f /dev/nst0 rewind; cat > /dev/nst0)$
You can restore tar backup over ssh session: # cd /
# ssh [email protected] "cat /backup/wwwdata.tar.gz" | tar zxvf -
If you wish to use above command in cron job or scripts then consider SSH keys to get rid of the passwords.

Some more examples:

$ tar cvjf - * | ssh [email protected] "(cd /dest/; tar xjf -)"
$ tar cvzf - mydir/ | ssh [email protected] "cat > /backups/myfile.tgz"
$ tar cvzf - /var/www/html | ssh [email protected] "dd of=/backups/www.tar.gz"
$ ssh [email protected] "cat /backups/www.tar.gz" | tar xvzf -
$ tar cvjf - * | ssh [email protected] "(cd /dest/; tar xjf - )"

Make sure you read the tar command/ssh command/bash command man page for more info:
$ man tar
$ man bash
$ man ssh

A note about SSHFS – a FUSE filesystem

You can use sshfs to mount a remote directory and run tar command:
mkdir /data/
sshfs [email protected]:/ /data/
tar -zcvf /data/file.tar.gz /home/vivek/

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Get real time updates directly on you device, subscribe now.