环境介绍:现有web服务器192.168.2.98和备份服务器192.168.70.182,需要每天把web服务器上产生的数据文件同步到备份服务器上来。
实现原理:通过rsync每天某一时刻备份服务器去web服务器拉取数据。
一、ssh公钥认证(为了免去登录输入密码)
1、生成密钥对 [root@servyouhome ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'. Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is: c2:81:43:6b:4f:cf:03:60:64:b2:d7:04:b6:65:80:f7 root@servyouhome
一路回车,不做任何修改
2、查看生产的公钥和私钥
[root@servyouhome ~]# ll .ssh/
total 8
-rw------- 1 root root 1675 Aug 23 11:08 id_rsa
-rw-r--r-- 1 root root 398 Aug 23 11:08 id_rsa.pub
3、copy公钥到目标服务器(192.168.2.98)
[root@servyouhome ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.2.98
输入yes,一路回车
The authenticity of host '192.168.2.98 (192.168.2.98)' can't be established.
RSA key fingerprint is 67:82:61:72:fa:37:06:3f:8e:03:3c:63:ac:1b:d1:d4.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.2.98' (RSA) to the list of known hosts.
root@192.168.2.98's password:
Now try logging into the machine, with "ssh 'root@192.168.2.98'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
4、登录验证
[root@servyouhome ~]# ssh root@192.168.2.98
Last login: Thu Aug 23 11:16:29 2012 from 192.168.2.145
[root@Servcenter ~]#
测试登录成功!!!
二、文件同步部分
rsync服务器端:192.168.2.98
rsync客户端:192.168.70.182
5、检查是否已经安装rsync
[root@Servcenter ~]# rpm -q rsync
rsync-2.6.8-3.1
......
[root@servyouhome ~]# rpm -q rsync
rsync-2.6.8-3.1
表明已经安装!!!
6、以守护进程方式来启动rsync,并设置该服务开机启动
[root@Servcenter ~]# rsync --daemon
[root@Servcenter ~]#chkconfig rsync on
7、确认rsync成功启动
[root@Servcenter ~]# netstat -npl | grep 873 (873是rsync的默认监听端口)
tcp 0 0 0.0.0.0:873 0.0.0.0:* LISTEN 3117/xinetd
tcp 0 0 :::873 :::* LISTEN 12153/rsync
[root@Servcenter ~]# ps -ef | grep rsync
root 12153 1 0 12:12 ? 00:00:00 rsync --daemon
root 12212 8120 0 12:13 pts/0 00:00:00 grep rsync
8、客户端启动rsync,并设置开机启动
[root@Servcenter ~]# rsync --daemon
[root@Servcenter ~]#chkconfig rsync on
9、客户端测试同步
执行
#rsync -azvI --delete --progress -e ssh root@192.168.2.98:/servyou/webroot /servyou/webroot/
#rsync -azvI --delete --progress -e ssh root@192.168.2.98:/servyou/backup/DB_DATA/ /servyou/backup/DB_DATA/
10、把上面命令作为脚本在客户端设置crontab任务,并于每天晚上2:00执行
[root@servyouhome servyou]# cat /etc/crontab
0 3 * * * /usr/local/bin/ntpdate 192.168.2.79 > /dev/null 2>&1
00 2 * * * root /servyou/cp.sh