rsync + ssh – 完成服务器之间的批量数据同步

现有需求以下:需对若干服务器作相同的环境配置,且配置工做至关复杂,若人工一台一台的处理比较耗时且容易出错。咱们能够考虑先完成一台服务器的配置工做,确认配置无误后,再经过脚本,将相应的配置工做同步到其余全部的服务器中。设有已完成配置的服务器:A (192.168.0.2) 和 待配置的服务器B ~ Z(192.168.0.101 ~ 126)。
实现上述需求,关键有两点:1). 经过ssh信任登陆,避免每次同步时要求输入密码;2). 经过rsync命令实现服务器之间文件的同步。具体实现细节以下:
1. 完成单向Trusted SSH Authorized
首先在A产生public/private dsa key pair:
……………………………………………………………………………………………………
[root@kplan-test3 .ssh]# ssh-keygen -d
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
f3:47:3b:b0:2a:50:f8:77:7e:ca:29:85:e8:d9:05:9b root@kplan-test3
[root@kplan-test3 .ssh]#
……………………………………………………………………………………………………
完成上述命令后,会在系统/root/.ssh目录生成两个文件:id_dsa与id_dsa.pub。如今复制id_dsa.pub到B服务器,并改名为 authorized_keys2
……………………………………………………………………………………………………
[root@kplan-test3 .ssh]# scp id_dsa.pub 192.168.0.101:/root/.ssh/authorized_keys2
root@192.168.0.101’s password:
id_dsa.pub 100% |*****************************************************| 612 00:00
[root@kplan-test3 .ssh]#
……………………………………………………………………………………………………
若是上述步骤顺利完成的话,如今您能够执行”ssh 192.168.0.101”,无需输入登陆密码,便可登陆到B服务器了。
2.使用rsync 作Remote sync﹕
rsync特性简介: rsync是unix-like系统下的数据镜像备份工具,从命名上就能够看出来了remote sync。它的特性以下:
一、能够镜像保存整个目录树和文件系统。
二、能够很容易作到保持原来文件的权限、时间等等。
三、无须特殊权限便可安装。
四、优化的流程,文件传输效率高。
五、可使用rcp、ssh等方式来传输文件,固然也能够经过直接的socket链接。
六、支持匿名传输。
参数意义以下﹕
-a, –archive
It is a quick way of saying you want recursion and want to preserve almost everything.
-v, –verbose
This option increases the amount of information you are given during the transfer.
-l, –links
When symlinks are encountered, recreate the symlink on the destination.
-R, –relative
Use relative paths. 保留相对路径…才不会让子目录跟 parent 挤在同一层…
–delete
是指若是Server端删除了一文件,那客户端也相应把这一文件删除,保持真正的一致。
-e ssh
创建起加密的链接。
三、同步脚本
建立脚本,实现自动配置工做。
……………………………………………………………………………………………………
[root@kplan-test3 backup]# vi install_env.sh
#!/bin/bash
WEBSERVER=’kplan-test1 kplan-test2 kplan-test3′
echo “auto install envirment … ————————”
for webserver in $WEBSERVER
do
    echo “install server:$webserver’s envirment.”
    echo ‘transport file : /etc/profile & /etc/hosts’
    rsync -v -r -l -H -p -g -t -S -e ssh –delete /etc/profile root@$webserver:/etc/profile
    rsync -v -r -l -H -p -g -t -S -e ssh –delete /etc/hosts root@$webserver:/etc/hosts
    echo ‘run shell command : /home/init_env.sh’
    ssh -q -o StrictHostKeyChecking=no root@$webserver “/home/init_env.sh”
    ssh -q -o StrictHostKeyChecking=no  root@$webserver “rm -f /home/init_env.sh”     echo ” $webserver is end  ————————- ” done sleep 1 clear …………………………………………………………………………………………………… 四、其余 若是你想用来作自动备份,则在crontab中加入备份脚本便可。如在天天0时0分作备份(设/root目录下已有完成备份的脚本 backup.sh): …………………………………………………………………………………………………… [root@kplan-test3 backup]# crontab -e 0 0 * * * /root/backup.sh
相关文章
相关标签/搜索