Rsync is a software utility which is very handy for synchronizing files and directories over different locations with minimized data transfer. It is used to copy files recursively with compression and over encrypted channels.
We are going to copy files using rsync over SSH in this tutorial.
Generate Public SSH Keys
In your server, you can generate public SSH keys without passwords by simply executing the command:
ssh-keygen -f ~/.ssh/id_rsa -q -P "" you can execute the command to print the key generated: cat ~/.ssh/id_rsa.pub
The public SSH key is something like this which can be placed on hosts to give you access.
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDrGM+ojLds2uS6aPCdwocSxXAyW6wRABu+NEhLoAEYUGTAJ+XUBUDC1IPdS6/t+lZlJw9LXJazv4InaZPgKgzEUlwuBFStB5/xgn35U/4SgXMPGOd0ipSwzTyeV72InMqHAIbfhG8CjNScPuqg/O8WOVNF5gaVdXcXV9L9uH9bFObjAMw6L+xg3bRdQ4+/la6FFbtoVo76lUGnj9+3RwF4oLHuvt2mM5UKCvhEkP7xHUxYzniqtSG2Xd8bgV++XqyYZou+teaH9KxqG8W0I1be5pTTzefFpJzsLYtASlk9xiSCd+ulVWNNLIlo+2B8/9DrDWA2jCB7gviwy7wJaX61 [email protected]
Ensure to copy and save this key somewhere as you will be needing it for destination server.
Now, Login to your destination server and save this key into your ~/.ssh/authorized_keys file.
If ssh folder is not present, you can create it manually using:
mkdir ~/.ssh You can change the permission of the folder: chmod 0700 ~/.ssh create a file under this directory with your favourite editor vi ~/.ssh/authorized_keys and again to change the permission of created file chmod 0644 ~/.ssh/authorized_keys
Using Rsync to Copy Files
Next, we will show you how to copy files using rsync. For example, let’s assume that we are copying a sample file from our server to destination server (188.8.131.52) and the file to be copied is /root/samplefile.txt
the command to execute is given below:
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /root/samplefile.txt 184.108.40.206:/root/ if your are using it form the first time it will give you Warning: Permanently added '220.127.116.11' (ECDSA) to the list of known hosts and ask you for the destination server password Password for [email protected]: just hit the password
NOTE: In case if you are using a normal user named prinsa and not root user, then you will have to append it in front of destination server. Also, make sure that you have already place the public key in that user’s ~/.ssh/authorized_keys file.
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /root/samplefile.txt [email protected]:/
Now you can verify the copied file from your destination server:
ls -la /root/samplefile.txt