文件同步方案
前提
免密鑰登陸線上服務器
A爲本地主機(即用於控制其他主機的機器) ;
B爲遠程主機(即被控制的機器Server), 假如ip爲172.24.253.2 ;
A和B的系統都是Linux
在A上的命令:
ssh-keygen -t rsa (連續三次回車,即在本地生成了公鑰和私鑰,不設置密碼)
ssh [email protected] "mkdir .ssh;chmod 0700 .ssh" (需要輸入密碼, 注:必須將.ssh的權限設爲700)
scp ~/.ssh/id_rsa.pub [email protected]:.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 [email protected] (不需要密碼, 登錄成功)
假如在生成密鑰對的時候指定了其他文件名(或者需要控制N臺機器,此時你會生成多對密鑰),則需要使用參數-i指定私鑰文件
ssh [email protected] -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