在Linux上,远程文件同步通过 rsync 实现,目前多数Linux上都已经安装了rsync。
由于rsync仅复制修改过的文件,因此能最大限度的减少需要同步的文件。
由于rsync同步时,每次都需要用户输入远程服务器的密码,因此如果希望通过脚本定时同步文件的话,需要使用证书登录。
下面是生成证书的步骤:
1.首先在需要执行 rsync 命令的B主机上,生成 RSA 密钥:$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/haifeng/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/haifeng/.ssh/id_rsa.
Your public key has been saved in /home/haifeng/.ssh/id_rsa.pub.
The key fingerprint is:
7b:75:98:eb:fd:13:ce:0f:c4:cf:2c:65:cc:73:70:53 haifeng@haifeng-EX38-DS4
The key's randomart image is:
+--[ RSA 2048]----+
| E|
| .|
| ...|
| + =.|
| S + +.*|
| . . + Bo|
| . . . = =|
| . . . * |
| . ..=|
+-----------------+
输入后,会提示创建.ssh/id_rsa、id_rsa.pub的文件,其中第一个为密钥,第二个为公钥。过程中会要求输入密码,为了ssh访问过程无须密码,可以直接回车 。
2.查看钥匙
[root@localhost .ssh]# ls ~/.ssh/
id_rsa id_rsa.pub known_hosts
可以发现 ssh目录下的两枚钥匙。
3.将公密钥 id_rsa.pub 文件通过FTP或SCP拷贝到远程A主机上
在远程A主机上,以执行 rsync 时的用户名登录,复制 id_rsa.pub 的内容到 ~/.ssh/authorized_keys:
$ cat id_rsa.pub >>~/.ssh/authorized_keys
$ chmod 700 ~/.ssh/authorized_keys
现在从B主机通过rsync或者SSH到A主机传递文件,就不会再提问密码了。
执行rsync实现文件同步
接着就可以使用 rsync 来同步B主机和A主机的文件夹。在B主机上执行命令:$ rsync -vaz root@123.123.123.88:/var/www/public_html/ /home/jack/public_html/
就能将远程服务器123.123.123.88上的目录/var/www/public_html/中的所有文件同步到本地目录 /home/jack/public_html/ 中。
将上面的rsync命令放到cron中定时执行,例如每8分钟执行一次。就能实现两台服务器之间的数据同步、备份了。