天天看點

linux下兩台伺服器檔案實時同步

linux下兩台伺服器檔案實時同步方案設計和實作

假設有如下需求:

假設兩個伺服器:

192.168.7.1 源伺服器 有目錄 /opt/test/

192.168.7.2 目标伺服器 有目錄 /opt/bak/test/

實作的目的就是保持這兩個伺服器某個檔案目錄保持實時同步

實作方式: 通過rsync+inotify-tools結合來實作

需要安裝軟體:

1. rsync 同步軟體

在 源伺服器 和 目标伺服器 都需要安裝

源伺服器: 是rsync用戶端,不需要配置

目标伺服器: 是rsync伺服器端,需要配置/etc/rsyncd.conf裡的内容

安裝後需要建立配置檔案:/etc/rsyncd.conf

配置檔案在: /etc/

檔案内容如下:

uid = root

gid = root

use chroot = no

max connections = 10

strict modes = yes

pid file=/var/run/rsyncd.pid

lock file=/var/run/rsyncd.lock

log file= =/var/run/rsyncd.log

[www]

path= /opt/bak/test

comment= analyse

read only = false

hosts allow = *

2. inotify-tools 工具

該工具為檔案實時監控工具,需要linux作業系統核心支援,核心支援需要至少版本為2.6.13

檢查作業系統是否支援,執行如下:

uname -r 檢視版本

傳回:

2.6.32-220.4.1.el6.x86_64

則表示版本2.6.32 大于2.6.13,則支援。

執行:

ll /proc/sys/fs/inotify

total 0

-rw-r--r-- 1 root root 0 Oct 18 12:18 max_queued_events

-rw-r--r-- 1 root root 0 Oct 18 12:18 max_user_instances

-rw-r--r-- 1 root root 0 Oct 18 12:18 max_user_watches

有三項輸出,則表示預設支援inotify,可以安裝inotify-tools工具.

如果不支援,需要采用新版本的linux作業系統

版本達到要求,就可以安裝了。

安裝inotify-tools後會在相關安裝目錄下生成如下兩個檔案:

ll /usr/local/bin/

total 88

-rwxr-xr-x 1 root root 44327 Oct 10 15:32 inotifywait

-rwxr-xr-x 1 root root 41417 Oct 10 15:32 inotifywatch

則表示安裝成功。

注意: 在 源伺服器上需要安裝,目标伺服器上不需要安裝inotify。

3. 相關腳本:

在源伺服器上建立腳本:

inotify_bak.sh

#!/bin/bash

src=/opt/test/

/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e close_write,delete,create,attrib $src | while read file

do

/usr/bin/rsync -arzuq $src 192.168.7.2::www/

echo " ${file} was rsynced" >>/opt/soft/log/rsync.log 2>&1

done

注意: 這裡的 www 是在目标伺服器/etc/rsyncd.conf裡配置的子產品名稱:[www]

賦予執行權限: chmod +x inotify_bak.sh

然後執行: inotify_bak.sh & 放入背景執行

4. 啟動

目标伺服器:先啟動rsync背景服務: /usr/bin/rsync --daemon

來源伺服器: 執行 inotify_bak.sh &

5. 測試

在來源伺服器目錄中建立目錄和檔案,inotify_bak.sh腳本會檢測到,然後同步到目标伺服器的相關目錄下

可以檢視日志檔案: /opt/soft/log/rsync.log 指令如下:觀察實時同步的情況。

tail -f /opt/soft/log/rsync.log

繼續閱讀