Pages

Sunday, November 27, 2022

Syncing two remote directories with rsync command

 rsync, a command that syncs the two remote directories.

Though straight forward by typing password, we my need to sync with key (PEM) files. We need to set remote shell and as parameter we can set the key file name.


An example:

Local to Remote:

rsync -rPav   -e 'ssh  -i ~/.ssh/id_rsa'  /local/source/directory/  user@remote_server:/remote/destination/directory/  

 

Remote to Local:

 rsync -rPav   -e 'ssh  -i ~/.ssh/id_rsa'  user@remote_server:/remote/source/directory/  /local/destination/directory/

 

Please note, the trailing slashes ( / ) in both source and destination directories.


To update (if source has newer) and delete parameters "u" and "--delete" need to use:

rsync -rPavu --delete

 

The things become even easier if we maintain a config file for ssh. For example, our .ssh/config file contains something like this:

HOST remote-machine
        IdentityFile ~/.ssh/id_rsa.pem
        Hostname our-remote-host.example.com
        User user

Then we can invoke like below:

Local to Remote:

rsync -rPav   -e 'ssh'  /local/source/directory/  remote-machine:/remote/destination/directory/  

 

Remote to Local:

 rsync -rPav   -e 'ssh'  remote-machine:/remote/source/directory/  /local/destination/directory/