文件同步方案
前提
免密钥登陆线上服务器
A为本地主机(即用于控制其他主机的机器) ;
B为远程主机(即被控制的机器Server), 假如ip为172.24.253.2 ;
A和B的系统都是Linux
在A上的命令:
ssh-keygen -t rsa (连续三次回车,即在本地生成了公钥和私钥,不设置密码)
ssh root@172.24.253.2 "mkdir .ssh;chmod 0700 .ssh" (需要输入密码, 注:必须将.ssh的权限设为700)
scp ~/.ssh/id_rsa.pub root@172.24.253.2:.ssh/id_rsa.pub (需要输入密码)
在B上的命令:
touch /root/.ssh/authorized_keys (如果已经存在这个文件, 跳过这条)
chmod 600 ~/.ssh/authorized_keys (# 注意: 必须将~/.ssh/authorized_keys的权限改为600, 该文件用于保存ssh客户端生成的公钥,可以修改服务器的ssh服务端配置文件/etc/ssh/sshd_config来指定其他文件名)
cat /root/.ssh/id_rsa.pub << /root/.ssh/authorized_keys (将id_rsa.pub的内容追加到 authorized_keys 中, 注意不要用 < ,否则会清空原有的内容,使其他人无法使用原有的密钥登录)
回到A机器:
ssh root@172.24.253.2 (不需要密码, 登录成功)
假如在生成密钥对的时候指定了其他文件名(或者需要控制N台机器,此时你会生成多对密钥),则需要使用参数-i指定私钥文件
ssh root@172.24.253.2 -i /path/to/your_id_rsa
scp也是一样,如:
scp -i /root/.ssh/id_rsa ./xxx 192.168.102.158:/home/wwy/bak
因为默认情况下ssh命令会使用~/.ssh/id_rsa作为私钥文件进行登录,如果需要连接多台服务器而又不希望每次使用ssh命令时指定私钥文件,可以在ssh的客户端全局配置文件/etc/ssh/ssh_config(或本地配置文件~/.ssh/config, 如果该文件不存在则建立一份)中增加如下配置
IdentityFile /path/to/your_id_rsa.
也可以为每个服务器指定一个Host配置:
Host 172.24.253.2 IdentityFile /path/to/your_id_rsa
如果连接时出现如下的错误:
Agent admitted failure to sign using the key
则使用 ssh-add 指令將私钥加进来(根据个人的密匙命名不同更改 id_rsa)
ssh-add ~/.ssh/id_rsa
安装
- rsync:apt-get install rsync 本地和线上服务器都要安装
- inotify:http://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
- tar -zxvf inotify-tools-3.14.tar.gz
- cd inotify-tools-3.14
- ./configure -prefix=/usr/local/inotify
- make
- make install 只在本地服务器安装
- 在本地服务器编写实时同步脚本
#!/bin/bash host_1=192.168.13.252 src=latest_version dst=images user=root /usr/local/inotify/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,attrib $src | while read file do rsync -avzP --delete --password-file=/etc/rsyncd.secrets $src $user@$host_1::$dst > /dev/null echo "${file} was rsynced" done exit 0
sudo nohup sh Inotifywait.sh &
然后关闭终端,检测脚本就在运行了。
设置开机自动启动脚本
vim /etc/rc.local #!/bin/sh # # This script will be executed *after* all the other init scripts. # You can put your own initialization stuff in here if you don't # want to do the full Sys V style init stuff. sudo sh /path/Inotifywait.sh exit 0