我的 H0 機器讓人 FTP 上傳檔案,監控程式偵測有檔案異動及開始 rsync 到 H1。示意圖如下:
H0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
if [ "$EUID" -ne 0 ]; then | |
echo "Please run as root." | |
exit | |
fi | |
IDENTITY="/home/user0/.ssh/id_rsa" | |
REMOTE="user0@H1:pool" | |
LOG="H0.log" | |
cd WWW_PATH | |
while true; do | |
raw=$(inotifywait -rq --excludei "thumbs.db" -e delete -e moved_to -e close_write -e create --timefmt "%y/%m/%d %T" --format "%T %e %w%f" WWW_PATH) | |
echo ${raw} >> ${LOG} | |
IFS=" " read -a actions <<< ${raw} | |
action=${actions[2]} | |
# Remove the prefix. | |
path=${actions[3]#WWW_PATH} | |
# Remove the file name part. | |
path=${path%/*} | |
RSYNC_RSH="ssh -i ${IDENTITY}" RSYNC_PATH -rltgoD --delete --progress ${path} ${REMOTE} >> ${LOG} | |
done | |
cd ~ |
L3 ~ L6: 因為 web root 權限需要,所以使用 sudo 提高權限。
L8: H0 & H1 透過 ssh 加密傳輸,得事先加信任公鑰。 L14 ~ L15: inotifywait 排除掉不想監控的檔案 ([Tt]hunms.db),接著只監控特定事件 (delete, moved_to, close_write, create)。為了記錄過程我把時間戳一並寫出,log 的樣子會長這樣:
15/10/04 21:37:05 CREATE /var/www/example.com/index.html
L9: 在 H1 機器上有個 pool 目錄放置這些需要同步的檔案,原因不想讓 rsync 直接寫到 web root,權限過大危險。
L21: 移除前綴字,避免同步路徑錯誤。
L24: 移除檔案名稱,讓 rsync 同步資料夾,而非單一檔案。
L26: rsync + ssh 同步資料夾到 H1。
L21: 移除前綴字,避免同步路徑錯誤。
L24: 移除檔案名稱,讓 rsync 同步資料夾,而非單一檔案。
L26: rsync + ssh 同步資料夾到 H1。
H1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
if [ "$EUID" -ne 0 ]; then | |
echo "Please run as root." | |
exit | |
fi | |
SRC="POOL_PATH" | |
LOG="H1.log" | |
cd $SRC | |
while true; do | |
raw=$(inotifywait -rq --excludei "thumbs.db" -e delete -e moved_to -e close_write -e create --timefmt "%y/%m/%d %T" --format "%T %e %w%f" $SRC) | |
echo ${raw} >> ${LOG} | |
IFS=" " read -a actions <<< ${raw} | |
action=${actions[2]} | |
# Remove the prefix. | |
path=${actions[3]#${SRC}/} | |
# Remove the file name part. | |
path=${path%/*} | |
RSYNC_PATH -rltgoD --delete --progress ${path} WWW_PATH >> ${LOG} | |
chown -R www-data: WWW_PATH | |
done | |
cd ~ |
L3 ~ L6: 因為要寫入到 web root,要求得是 root 。
L13 ~ L26: 做的事情和 H0 一樣,只是來源和目的互換。
沒有留言:
張貼留言