In this tutorial we are going to configure rsync and crontab to synchronize files between two machines without using a password and program execution times.
To prevent each time a synchronization script is launched from asking for the password of the user of the remote server with which it is being synchronized, we are going to create a file with a key that we will store on the remote server to avoid having to enter the password each time let's synchronize
Generate key
To generate the key on the destination server we will use the following command:
ssh-keygen -t rsa -N "Loremipsumdolorsitamet,consecteturadipiscingelit.Maecenasipsum." -f paxwkfile_rsa
With the following result:
root@webserver:~# ssh-keygen -t rsa -N "Loremipsumdolorsitamet,consecteturadipiscingelit.Maecenasipsum." -f paxwkfile_rsa Generating public/private rsa key pair. Your identification has been saved in paxwkfile_rsa. Your public key has been saved in paxwkfile_rsa.pub. The key fingerprint is: SHA256:fLPHCILhUDzSStsrRxGXXSyeOqn4NLC/qo0V18P7C5E root@webserver02 The key's randomart image is: +---[RSA 2048]----+ | oo..o o. | | o.=.. or . | | ..=.o . or | | ooo= oo | | o.+.EoS o | | .=o += o = | | o+oo oo | | +.o.. or . | |o.oo+. either. | +----[SHA256]-----+ root@webserver:~#
If everything went well, we will have two new files in our directory, one with the private key and the other with the public key:
root@webserver02:~# ls -ltr pax -rw-r--r-- 1 root root 398 May 19 08:18 paxwkfile_rsa.pub -rw------- 1 root root 1876 May 19 08:18 paxwkfile_rsa root@webserver02:~#
The next step will be to move them to the .ssh directory of our home, which will be where all the keys are:
root@webserver:~# cp *pax* ./.ssh/
Copy the public key to the server
With our generated keys we will have to copy our public key on the server, once again in the .ssh directory of our user's home:
root@webserver02:~/.ssh# ssh-copy-id -i ./paxwkfile_rsa.pub root@192.168.1.252 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ". /paxwkfile_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO : 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@192.168.1.252's password: Number of key(s) added: 1 Now try logging into the machine, with : "ssh 'root@192.168.1.252'" and check to make sure that only the key(s) you wanted were added.
With this command, what we do is add the key that we have just generated to the file: /root/.ssh/authorized_keys
In this way, every time we connect to our server by ssh, it will not ask us for a password again.
Folder Synchronization
I leave you the command that I use to synchronize folders with the server:
rsync -avhe ssh --delete /dir/dir/source_folder/ user@server:/dir/rrsync/target_folder/