天天看點

Linux系統實時資料同步inotify+rsync

Linux系統實時資料同步inotify+rsync

inotify是Linux核心的一個功能,它能監控檔案系統的變化,比如删除、讀、寫和解除安裝等操作。它監控到這些事件的發生後會預設往标準輸出列印事件資訊。要使用inotify,Linux核心版本必須是大于2.6.13,在這之前的核心都沒有這個功能。我們可以利用inotify去監控我們要監控的資源,當資源發生變化時,我們撲捉它的事件,進而觸發同步資料等操作。

一、inotify簡介

  inotify是Linux核心的一個功能,它能監控檔案系統的變化,比如删除、讀、寫和解除安裝等操作。它監控到這些事件的發生後會預設往标準輸出列印事件資訊。要使用inotify,Linux核心版本必須是大于2.6.13,在這之前的核心都沒有這個功能。我們可以利用inotify去監控我們要監控的資源,當資源發生變化時,我們撲捉它的事件,進而觸發同步資料等操作。

二、inotify軟體介紹

  inotify是核心的一個功能,衆所周知核心的功能我們必須要配合工具才能使用,通常情況下使用者要使用核心的功能,都需要使用者空間的軟體去調用才可以達到使用核心的功能的目的,使用者是無法直接操核心的。實作inotify軟體有inotify-tools、sersync、lrsyncd。我們這裡以inotify-tools這個軟體包為例進行實驗;inotify-tools包主要有兩個檔案,一個是inotifywait: 在被監控的檔案或目錄上等待特定檔案系統事件(open close delete等)發生,常用于實時同步的目錄監控;一個是inotifywatch:收集被監控的檔案系統使用的統計資料,指檔案系統事件發生的次數統計。通常情況下我們使用iontifywait就可以了。接下來我們來安裝inotify-tools

三、inotify軟體安裝和使用

  首先我們要确認我們手上的Linux系統是否支援inotify這個功能

[root@test ~]# uname -r
3.10.0-957.27.2.el7.x86_64
[root@test ~]# ll /proc/sys/fs/inotify/
總用量 0
-rw-r--r-- 1 root root 0 1月  31 16:29 max_queued_events
-rw-r--r-- 1 root root 0 1月  31 16:29 max_user_instances
-rw-r--r-- 1 root root 0 1月  31 16:29 max_user_watches
[root@test ~]#
      

  提示:如果我們的核心版本高于2.6.13,并且有/proc/sys/fs/inotify/目錄,說明我們的系統上支援inotify功能的

  inotify核心參數說明

  我們在/proc/sys/fs/inotify這個目錄下看到有三個檔案,這三個檔案就是記錄inotify的核心參數的檔案。其中max_queued_events這個檔案記錄inotify事件隊列最大長度,如值太小會報Event Queue Overflow 錯誤,預設值:16384,當然這個值是可以更改的,臨時更改可以用echo 指令加上值給重定向到這個檔案中。永久修改需要修改編輯/etc/sysctl.conf

[root@test ~]# cat /proc/sys/fs/inotify/max_queued_events 
16384
[root@test ~]# echo 'fs.inotify.max_queued_events=999999' >> /etc/sysctl.conf                      
[root@test ~]# cat /etc/sysctl.conf
# sysctl settings are defined through files in
# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
#
# Vendors settings live in /usr/lib/sysctl.d/.
# To override a whole file, create a new file with the same in
# /etc/sysctl.d/ and put new settings there. To override
# only specific settings, add a file with a lexically later
# name in /etc/sysctl.d/ and put new settings there.
#
# For more information, see sysctl.conf(5) and sysctl.d(5).
fs.inotify.max_queued_events=999999
[root@test ~]# sysctl -p
fs.inotify.max_queued_events = 999999
[root@test ~]# cat /proc/sys/fs/inotify/max_queued_events 
999999
[root@test ~]# 
      

  提示:修改核心其他參數,也是是類似的方法。

  max_user_watches:這個檔案主要存放單個程序監控檔案的數量,預設是8129;生産環境中如果監控的檔案數量龐大,可以通過上面的方式去修改這個值

  max_user_instances:這個檔案存放使用者建立inotify執行個體的最大值,預設是128;同樣也是可以通過上面的方式修改

  inotify軟體安裝

  參考文檔https://github.com/rvoicilas/inotify-tools/wiki

  inotify是基于epel源,在用yum安裝前請先配好yum源

[root@test ~]# yum info inotify-tools
已加載插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
可安裝的軟體包
名稱    :inotify-tools
架構    :x86_64
版本    :3.14
釋出    :9.el7
大小    :51 k
源    :epel/x86_64
簡介    : Command line utilities for inotify
網址    :http://inotify-tools.sourceforge.net/
協定    : GPLv2
描述    : inotify-tools is a set of command-line programs for Linux providing
         : a simple interface to inotify. These programs can be used to monitor
         : and act upon filesystem events.

[root@test ~]# 
      

  提示:如果用yum可以看到inotify-tools的說明資訊,說明你的Linux yum倉庫裡有這個軟體包,可以直接yum 安裝即可

[root@test ~]# yum install -y inotify-tools
已加載插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
base                                                                                                      | 3.6 kB  00:00:00     
dockerrepo                                                                                                | 2.9 kB  00:00:00     
epel                                                                                                      | 5.3 kB  00:00:00     
extras                                                                                                    | 2.9 kB  00:00:00     
updates                                                                                                   | 2.9 kB  00:00:00     
updates/7/x86_64/primary_db                                                                               | 5.9 MB  00:00:01     
正在解決依賴關系
--> 正在檢查事務
---> 軟體包 inotify-tools.x86_64.0.3.14-9.el7 将被 安裝
--> 解決依賴關系完成

依賴關系解決

=================================================================================================================================
 Package                            架構                        版本                             源                         大小
=================================================================================================================================
正在安裝:
 inotify-tools                      x86_64                      3.14-9.el7                       epel                       51 k

事務概要
=================================================================================================================================
安裝  1 軟體包

總下載下傳量:51 k
安裝大小:111 k
Downloading packages:
inotify-tools-3.14-9.el7.x86_64.rpm                                                                       |  51 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在安裝    : inotify-tools-3.14-9.el7.x86_64                                                                              1/1 
  驗證中      : inotify-tools-3.14-9.el7.x86_64                                                                              1/1 

已安裝:
  inotify-tools.x86_64 0:3.14-9.el7                                                                                              

完畢!
[root@test ~]# 
      

  提示:我們安裝好軟體包要習慣的去看這個軟體包裝了那些東西,它的配置檔案大概放在哪個位置等資訊

[root@test ~]# rpm -ql inotify-tools
/usr/bin/inotifywait
/usr/bin/inotifywatch
/usr/lib64/libinotifytools.so.0
/usr/lib64/libinotifytools.so.0.4.1
/usr/share/doc/inotify-tools-3.14
/usr/share/doc/inotify-tools-3.14/AUTHORS
/usr/share/doc/inotify-tools-3.14/COPYING
/usr/share/doc/inotify-tools-3.14/ChangeLog
/usr/share/doc/inotify-tools-3.14/NEWS
/usr/share/doc/inotify-tools-3.14/README
/usr/share/man/man1/inotifywait.1.gz
/usr/share/man/man1/inotifywatch.1.gz
[root@test ~]# 
      

  提示:從上面查詢的資訊我們可以清楚的知道,inotify-tools這兩個包主要安裝了兩個程式,一個是/usr/bin/inotifywait,一個是/usr/bin/inotifywatch,其他都是它的幫助文檔;在上面的介紹了這兩個程式的作用;安裝好了inotify工具後,我們再來看看inotifywait這個工具的用法和選項

  inotifywait指令常見選項說明

[root@test ~]# inotifywait --help
inotifywait 3.14
Wait for a particular event on a file or set of files.
Usage: inotifywait [ options ] file1 [ file2 ] [ file3 ] [ ... ]
Options:
        -h|--help       Show this help text.
        @<file>         Exclude the specified file from being watched.
        --exclude <pattern>
                        Exclude all events on files matching the
                        extended regular expression <pattern>.
        --excludei <pattern>
                        Like --exclude but case insensitive.
        -m|--monitor    Keep listening for events forever.  Without
                        this option, inotifywait will exit after one
                        event is received.
        -d|--daemon     Same as --monitor, except run in the background
                        logging events to a file specified by --outfile.
                        Implies --syslog.
        -r|--recursive  Watch directories recursively.
        --fromfile <file>
                        Read files to watch from <file> or `-' for stdin.
        -o|--outfile <file>
                        Print events to <file> rather than stdout.
        -s|--syslog     Send errors to syslog rather than stderr.
        -q|--quiet      Print less (only print events).
        -qq             Print nothing (not even events).
        --format <fmt>  Print using a specified printf-like format
                        string; read the man page for more details.
        --timefmt <fmt> strftime-compatible format string for use with
                        %T in --format string.
        -c|--csv        Print events in CSV format.
        -t|--timeout <seconds>
                        When listening for a single event, time out after
                        waiting for an event for <seconds> seconds.
                        If <seconds> is 0, inotifywait will never time out.
        -e|--event <event1> [ -e|--event <event2> ... ]
                Listen for specific event(s).  If omitted, all events are 
                listened for.

Exit status:
        0  -  An event you asked to watch for was received.
        1  -  An event you did not ask to watch for was received
              (usually delete_self or unmount), or some error occurred.
        2  -  The --timeout option was given and no events occurred
              in the specified interval of time.

Events:
        access          file or directory contents were read
        modify          file or directory contents were written
        attrib          file or directory attributes changed
        close_write     file or directory closed, after being opened in
                        writeable mode
        close_nowrite   file or directory closed, after being opened in
                        read-only mode
        close           file or directory closed, regardless of read/write mode
        open            file or directory opened
        moved_to        file or directory moved to watched directory
        moved_from      file or directory moved from watched directory
        move            file or directory moved to or from watched directory
        create          file or directory created within watched directory
        delete          file or directory deleted within watched directory
        delete_self     file or directory was deleted
        unmount         file system containing file or directory unmounted
[root@test ~]# 
      

  提示:-m,--monitor表示始終保持事件監聽,如果不加這個選項,預設它隻是監控一次,也就是說隻要我們監控的目錄裡的資源發生一次變化後,它就退出監控了;通常情況我們是結合-m選項持續的監控一個目錄下的資源變化情況;-d表示以守護程序方式執行,和-m相似,配合-o使用。-d選項我們可以了解為背景守護程序的方式監控我們的資源,背景守護程序的方式執行我們是看不到說監控的資源變化情況,我們可以結合-o來指定一個檔案,把資源變化情況類似寫日志的方式給記錄下來; -r, --recursive表示遞歸監控目錄資料資訊變化;-q,--quiet表示輸出少量事件資訊;--timefmt <fmt>表示指定輸出事件的時間格式;--format <fmt> 表示指定的輸出格式;即實際監控輸出内容; -e 表示指定監聽指定的事件,如果省略,表示所有事件都進行監聽;--exclude <pattern>表示指定排除檔案或目錄,使用擴充的正規表達式比對的模式實作;--excludei <pattern> 和exclude相似,不區分大小寫; -o, --outfile <file>列印事件到檔案中,相當于标準正确輸出;-s, --syslogOutput 發送錯誤到syslog相當于标準錯誤輸出

  --timefmt <fmt>時間格式

    %Y:表示年份資訊,包含世紀資訊

    %y:表示年份資訊,不包含世紀資訊

    %m:表示月份,範圍01-12

    %d:表示每月的第幾天,範圍01-31

    %H:表示小時資訊,使用24小時制度,範圍00-24

    %M:表示分鐘,範圍00-59

  --format<fmt>輸出資訊格式定義

    %T:輸出時間格式中定義的時間格式,這個表示調用我們前面定義時間格式,通常情況--timefmt選項和--format結合使用

    %w:表示事件出現時,監控檔案或目錄的名稱資訊。也就是監控資源名稱資訊

    %f:時間出現時,顯示監控目錄下觸發事件的檔案或目錄資訊

    %e:顯示發生的事件資訊,不同僚件預設用逗号分隔

    %Xe:顯示發生的事件,不同的時間指定用"X"分割

[root@test ~]# inotifywait -m --timefmt "%Y-%m-%d %H:%M" --format "%T %w event:%;e" /root/dir2
Setting up watches.
Watches established.
2020-01-31 18:07 /root/dir2/ event:OPEN;ISDIR
2020-01-31 18:07 /root/dir2/ event:CLOSE_NOWRITE;CLOSE;ISDIR
2020-01-31 18:07 /root/dir2/ event:OPEN;ISDIR
2020-01-31 18:07 /root/dir2/ event:CLOSE_NOWRITE;CLOSE;ISDIR
2020-01-31 18:07 /root/dir2/ event:OPEN;ISDIR
2020-01-31 18:07 /root/dir2/ event:CLOSE_NOWRITE;CLOSE;ISDIR
2020-01-31 18:07 /root/dir2/ event:OPEN;ISDIR
2020-01-31 18:07 /root/dir2/ event:CLOSE_NOWRITE;CLOSE;ISDIR
      

  提示:指定資訊不輸出變化資源的檔案名和目錄,輸出資訊格式如上

[root@test ~]# inotifywait -m --timefmt "%Y-%m-%d %H:%M" --format "%T %w%f event:%;e" /root/dir2
Setting up watches.
Watches established.
2020-01-31 18:09 /root/dir2/test event:OPEN;ISDIR
2020-01-31 18:09 /root/dir2/test event:CLOSE_NOWRITE;CLOSE;ISDIR
2020-01-31 18:09 /root/dir2/ event:OPEN;ISDIR
2020-01-31 18:09 /root/dir2/ event:CLOSE_NOWRITE;CLOSE;ISDIR
2020-01-31 18:09 /root/dir2/f1 event:CREATE
2020-01-31 18:09 /root/dir2/f1 event:OPEN
2020-01-31 18:09 /root/dir2/f1 event:ATTRIB
2020-01-31 18:09 /root/dir2/f1 event:CLOSE_WRITE;CLOSE
2020-01-31 18:09 /root/dir2/f1 event:MOVED_FROM
2020-01-31 18:09 /root/dir2/ff event:MOVED_TO
      

  提示:指定資訊輸出變化資源的檔案名和目錄,輸出資訊格式如上

[root@test ~]# inotifywait -m --timefmt "%Y-%m-%d %H:%M" --format "%T %w%f %e" /root/dir2       
Setting up watches.
Watches established.
2020-01-31 18:10 /root/dir2/ OPEN,ISDIR
2020-01-31 18:10 /root/dir2/ CLOSE_NOWRITE,CLOSE,ISDIR
2020-01-31 18:10 /root/dir2/ OPEN,ISDIR
2020-01-31 18:10 /root/dir2/ CLOSE_NOWRITE,CLOSE,ISDIR
2020-01-31 18:10 /root/dir2/ OPEN,ISDIR
2020-01-31 18:10 /root/dir2/ CLOSE_NOWRITE,CLOSE,ISDIR
2020-01-31 18:10 /root/dir2/ OPEN,ISDIR
2020-01-31 18:10 /root/dir2/ CLOSE_NOWRITE,CLOSE,ISDIR
2020-01-31 18:10 /root/dir2/test OPEN,ISDIR
2020-01-31 18:10 /root/dir2/test CLOSE_NOWRITE,CLOSE,ISDIR
      

  提示:不指定輸出事件資訊分割符,預設是逗号分隔

  -e選項指定監控事件類型說明

    create:表示檔案或目錄的建立

    delete:表示檔案或目錄被删除

    modify:表示檔案或目錄内容的修改

    attrib:表示檔案或目錄的屬性發生變化

    close_write:表示檔案或目錄關閉,在寫入模式打開之後關閉的

    close_nowrite:表示檔案或目錄關閉,在隻讀模式打開之後關閉的

    close:表示檔案或目錄關閉,不管是讀還是寫模式

    open:檔案或目錄被打開

    moved_to:表示檔案被移動到監控目錄中

    moved_from:表示檔案或目錄從監控的目錄中被移動

    move:檔案或目錄不管移動到或移出監控目錄都觸發事件

    access:表示檔案或目錄内容讀取

    delete_self:表示檔案或目錄被删除,目錄本身被删除

    unmount:表示取消挂載

Linux系統實時資料同步inotify+rsync

   提示:-e選項指定監控目錄下檔案或目錄的事件,它隻響應對應目錄下的檔案發生了指定事件後,才給予響應。以上表示隻要/root/dir2目錄下的檔案或目錄發生了create,delete,move這三種事件的任何一種,它都給予響應,我們檢視/root/dir2下的檔案它是不監控的,也不予響應。

  了解了inotifywait指令的各種選項的使用後,我們就可以根據自己的實際需求來定義怎麼監控我們的資源,當資源發生變化時,我們後續該怎麼處理,這個不是inotify關心的事,它隻負責告訴我們監控的資源發生了什麼樣的變化。如果我們想要備份變化後的資源,我們就需要用到别的服務,比如rsync;rsync這個軟體是一個同步資料軟體,它可以通過腳本和inotify結合實作,當資源檔案發生變化時,觸發rsync去同步資料,這樣實作資料實時的同步。接下來我們在來搭建rsync服務

四、rsync服務安裝配置

  1、檢視系統是否安裝的有rsync,如果沒有就安裝

[root@test ~]# rpm -qa rsync
rsync-3.1.2-6.el7_6.1.x86_64
[root@test ~]# yum info rsync
已加載插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
已安裝的軟體包
名稱    :rsync
架構    :x86_64
版本    :3.1.2
釋出    :6.el7_6.1
大小    :815 k
源    :installed
來自源:updates
簡介    : A program for synchronizing files over a network
網址    :http://rsync.samba.org/
協定    : GPLv3+
描述    : Rsync uses a reliable algorithm to bring remote and host files into
         : sync very quickly. Rsync is fast because it just sends the differences
         : in the files over the network instead of sending the complete
         : files. Rsync is often used as a very powerful mirroring process or
         : just as a more capable replacement for the rcp command. A technical
         : report which describes the rsync algorithm is included in this
         : package.

[root@test ~]# 
      

  2、檢視rsync配置檔案路徑

[root@test ~]# rpm -ql rsync
/etc/rsyncd.conf
/etc/sysconfig/rsyncd
/usr/bin/rsync
/usr/lib/systemd/system/rsyncd.service
/usr/lib/systemd/system/rsyncd.socket
/usr/lib/systemd/system/[email protected]
/usr/share/doc/rsync-3.1.2
/usr/share/doc/rsync-3.1.2/COPYING
/usr/share/doc/rsync-3.1.2/NEWS
/usr/share/doc/rsync-3.1.2/OLDNEWS
/usr/share/doc/rsync-3.1.2/README
/usr/share/doc/rsync-3.1.2/support
/usr/share/doc/rsync-3.1.2/support/Makefile
/usr/share/doc/rsync-3.1.2/support/atomic-rsync
/usr/share/doc/rsync-3.1.2/support/cvs2includes
/usr/share/doc/rsync-3.1.2/support/deny-rsync
/usr/share/doc/rsync-3.1.2/support/file-attr-restore
/usr/share/doc/rsync-3.1.2/support/files-to-excludes
/usr/share/doc/rsync-3.1.2/support/git-set-file-times
/usr/share/doc/rsync-3.1.2/support/instant-rsyncd
/usr/share/doc/rsync-3.1.2/support/logfilter
/usr/share/doc/rsync-3.1.2/support/lsh
/usr/share/doc/rsync-3.1.2/support/lsh.sh
/usr/share/doc/rsync-3.1.2/support/mapfrom
/usr/share/doc/rsync-3.1.2/support/mapto
/usr/share/doc/rsync-3.1.2/support/mnt-excl
/usr/share/doc/rsync-3.1.2/support/munge-symlinks
/usr/share/doc/rsync-3.1.2/support/rrsync
/usr/share/doc/rsync-3.1.2/support/rsync-no-vanished
/usr/share/doc/rsync-3.1.2/support/rsync-slash-strip
/usr/share/doc/rsync-3.1.2/support/rsyncstats
/usr/share/doc/rsync-3.1.2/support/savetransfer.c
/usr/share/doc/rsync-3.1.2/tech_report.tex
/usr/share/man/man1/rsync.1.gz
/usr/share/man/man5/rsyncd.conf.5.gz
[root@test ~]# 
      

  提示:可從上面的資訊了解到rsync的配置檔案是/etc/rsyncd.conf,二進制檔案是/usr/bin/rsync

  3、/etc/rsyncd.conf配置檔案内容說明

[root@test ~]# cat /etc/rsyncd.conf
# /etc/rsyncd: configuration file for rsync daemon mode

# See rsyncd.conf man page for more options.

# configuration example:

# uid = nobody
# gid = nobody
# use chroot = yes
# max connections = 4
# pid file = /var/run/rsyncd.pid
# exclude = lost+found/
# transfer logging = yes
# timeout = 900
# ignore nonreadable = yes
# dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2

# [ftp]
#        path = /home/ftp
#        comment = ftp export area
[root@test ~]# 
      

  提示:我們打開rsync的配置檔案,裡面内容告訴我們,這個配置檔案用于rsync工作為獨立守護程序的服務配置,我們可以通過man rsyncd.conf來檢視裡面的選項說明

  4、編輯/etc/rsyncd.conf

[root@test ~]# cat /etc/rsyncd.conf
# /etc/rsyncd: configuration file for rsync daemon mode

# See rsyncd.conf man page for more options.

# configuration example:

# uid = nobody
# gid = nobody
# use chroot = yes
# max connections = 4
# pid file = /var/run/rsyncd.pid
# exclude = lost+found/
# transfer logging = yes
# timeout = 900
# ignore nonreadable = yes
# dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2

# [ftp]
#        path = /home/ftp
#        comment = ftp export area
uid = root
gid = root
use chroot = no
max connections = 0
ignore errors
exclude = lost+found/
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
reverse lookup = no
hosts allow = 192.168.0.0/24
[backup]
path = /backup/
comment = backup
read only = no
auth users = rsyncuser
secrets file = /etc/rsync.pass
[root@test ~]# 
      

  提示:uid,gid表示rsync這個服務是以那個使用者的身份去運作;use chroot表示是否可切換指定path裡的路徑,如果是yes表示在傳輸檔案之前首先 chroot 到 path 參數所指定的目錄下。這樣做的原因是實作額外的安全防護,但是缺點是需要 root并且不能備份指向 path 外部的符号連接配接所指向的目錄檔案;max connections表示指定最大并發連接配接數,0表示不限制;ignore errors表示忽略守護程序上的I/O錯誤;exclude表示排除監控的資源清單,也就是exclude後面的資源不監控;log file、pid file、lock file指定日志檔案,pid檔案,lock檔案的路徑;reverse lookup表示是否使用名稱解析(控制守護程序是否對用戶端IP位址執行反向查找以确定其主機名);hosts allow表示指定允許的主機或網段内的主機來通路rsync伺服器;[backup] 這個表示共享出來的目錄共享名稱,這個同samba的配置一樣,這個名稱隻是對用戶端看到共享出來的目錄名稱,它不是真的伺服器路徑名稱;path表示指定真實存放同步資料的路徑,也就是共享出去的名稱對應到系統上的那個目錄;comment表示描述說明;auth users表示那些使用者可以通路這個目錄;secrets file表示auth users的使用者的密碼資訊檔案

  5、準備備份資料目錄和建立secrets file所指定的使用者密碼檔案,并把auth users所指定的使用者和密碼資訊寫入到該檔案中

[root@test ~]# mkdir /backup
[root@test ~]# echo 'rsyncuser:admin' > /etc/rsync.pass
[root@test ~]# cat /etc/rsync.pass
rsyncuser:admin
[root@test ~]# chmod 600 /etc/rsync.pass
[root@test ~]# ll /etc/rsync.pass
-rw------- 1 root root 16 1月  31 19:27 /etc/rsync.pass
[root@test ~]# 
      

  提示:/etc/rsync.pass這個檔案是secrets file指定的檔案,它相當于一個虛拟的使用者檔案,不需要存在Linux系統中,這個檔案主要儲存用于同步資料時,所用到的使用者;通常情況下為了rsync的使用者資訊安全,建議把這個檔案的權限修改成600

  6、啟動rsync服務以Daemon方式運作,并檢查端口運作情況

[root@test ~]# ss -ntl
State       Recv-Q Send-Q                   Local Address:Port                                  Peer Address:Port              
LISTEN      0      100                          127.0.0.1:25                                               *:*                  
LISTEN      0      25                                   *:514                                              *:*                  
LISTEN      0      128                                  *:41319                                            *:*                  
LISTEN      0      50                                   *:3306                                             *:*                  
LISTEN      0      128                                  *:111                                              *:*                  
LISTEN      0      100                                ::1:25                                              :::*                  
LISTEN      0      25                                  :::514                                             :::*                  
LISTEN      0      128                                 :::41319                                           :::*                  
LISTEN      0      128                                 :::111                                             :::*                  
LISTEN      0      128                                 :::80                                              :::*                  
[root@test ~]# rsync --daemon
[root@test ~]# ss -ntl
State       Recv-Q Send-Q                   Local Address:Port                                  Peer Address:Port              
LISTEN      0      100                          127.0.0.1:25                                               *:*                  
LISTEN      0      25                                   *:514                                              *:*                  
LISTEN      0      128                                  *:41319                                            *:*                  
LISTEN      0      5                                    *:873                                              *:*                  
LISTEN      0      50                                   *:3306                                             *:*                  
LISTEN      0      128                                  *:111                                              *:*                  
LISTEN      0      100                                ::1:25                                              :::*                  
LISTEN      0      25                                  :::514                                             :::*                  
LISTEN      0      128                                 :::41319                                           :::*                  
LISTEN      0      5                                   :::873                                             :::*                  
LISTEN      0      128                                 :::111                                             :::*                  
LISTEN      0      128                                 :::80                                              :::*                  
[root@test ~]# 
      

  提示:rsync預設端口是873  當然也可以通過在配置檔案中用port 來指定

  7、在用戶端上建立密碼檔案

[root@test-centos6-node1 ~]# echo "admin" >/etc/rsync.pass  
[root@test-centos6-node1 ~]# chmod 600 /etc/rsync.pass
[root@test-centos6-node1 ~]# ll /etc/rsync.pass
-rw------- 1 root root 6 Feb  1 03:38 /etc/rsync.pass
[root@test-centos6-node1 ~]#       

  8、在用戶端測試rsync是否可以把指定檔案同步到rsync共享出來的backup下(這裡的backup不是指伺服器上的真實路徑,是中括号裡指定的名稱,這個名稱可以随便起,沒有特殊要求)

[root@test-centos6-node1 ~]# tree 
.
└── test

1 directory, 0 files
[root@test-centos6-node1 ~]# echo "this is test file" >test/f1
[root@test-centos6-node1 ~]# rsync -avz --password-file=/etc/rsync.pass /root/test/ [email protected]::backup
sending incremental file list
./
f1

sent 93 bytes  received 30 bytes  246.00 bytes/sec
total size is 18  speedup is 0.15
[root@test-centos6-node1 ~]#       

  提示:可以看到在用戶端已經把指定的資源給同步到rsync伺服器上了,接下來我們看看rsync指定存放同步資料的目錄是否有用戶端同步過來的檔案

[root@test ~]# ll /backup
總用量 4
-rw-r--r-- 1 root root 18 2月   1 2020 f1
[root@test ~]# cat /backup/f1 
this is test file
[root@test ~]# 
      

  提示:在服務端可以看到用戶端同步過來的檔案;到此rsync服務就搭建完畢了。接下來我們編寫腳本結合inotify和rsync實作實時同步

五、在用戶端編寫腳本實作inotify+rsync實作實時同步

  實驗環境:centos6是用戶端,在上面安裝inotify-tools工具;centos7是rsync服務端;實驗目的是實作實時監控centos6上的/root/test/目錄下的所有資源,如果有變化就把檔案通過rsync推送到rsync伺服器上,實作實時同步

  1、在centos6上安裝inotify-tools

[root@test-centos6-node1 ~]# yum install -y inotify-tools
Loaded plugins: fastestmirror
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirrors.cn99.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
base                                                                              | 3.7 kB     00:00     
epel                                                                              | 5.3 kB     00:00     
extras                                                                            | 3.4 kB     00:00     
my_base                                                                           | 4.0 kB     00:00     
percona-release-noarch                                                            | 2.9 kB     00:00     
percona-release-x86_64                                                            | 2.9 kB     00:00     
updates                                                                           | 3.4 kB     00:00     
Resolving Dependencies
--> Running transaction check
---> Package inotify-tools.x86_64 0:3.14-2.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=========================================================================================================
 Package                      Arch                  Version                    Repository           Size
=========================================================================================================
Installing:
 inotify-tools                x86_64                3.14-2.el6                 epel                 46 k

Transaction Summary
=========================================================================================================
Install       1 Package(s)

Total download size: 46 k
Installed size: 104 k
Downloading Packages:
inotify-tools-3.14-2.el6.x86_64.rpm                                               |  46 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : inotify-tools-3.14-2.el6.x86_64                                                       1/1 
  Verifying  : inotify-tools-3.14-2.el6.x86_64                                                       1/1 

Installed:
  inotify-tools.x86_64 0:3.14-2.el6                                                                      

Complete!
[root@test-centos6-node1 ~]#
      

  2、編寫腳本

[root@test-centos6-node1 ~]# cat inotify_rsync.sh 
#!/bin/bash
SRC='/root/test/'
DEST='[email protected]::backup'
inotifywait -mrq --timefmt '%Y-%m-%d %H:%M' --format '%T %w %f' -e create,delete,moved_to,close_write ${SRC} |while read DATE TIME DIR FILE;do
        FILEPATH=${DIR}${FILE}
        rsync -az --delete --password-file=/etc/rsync.pass $SRC $DEST &&
        echo "At ${TIME} on ${DATE}, file $FILEPATH was backuped up via rsync" >> /var/log/changelist.log
done
[root@test-centos6-node1 ~]#
      

  提示:解釋下上面的腳本,首先我們定義要監控的目錄src和rsync的位址dest(這個位址就是用戶端rsync連接配接rsync服務端的位址),然後通過inotifywait來指定監控的資源和事件,以及輸出資訊的格式,然後每一次觸發事件的輸出資訊就交給while read處理,while read 把事件輸出資訊分别用DATA TIME DIR FILE來儲存;然後把DIR和FILE做合并,得到變化資源的真實路徑,然後通過rsync把變化的資源推到rsync伺服器上,然後把對應的事件資訊寫到/var/log/changelist.log中。

  測試腳本是否能夠達到實時備份的效果

Linux系統實時資料同步inotify+rsync

   提示:在用戶端運作腳本,在rsync服務端監控/backup裡的變化。然後在用戶端操作在/root/test/目錄下進行檔案的增加删除修改,看看是否能夠及時的同步到rysnc伺服器上

Linux系統實時資料同步inotify+rsync

   提示:可以看到我們在用戶端建立一個檔案是能夠及時的同步到rysnc伺服器上的

Linux系統實時資料同步inotify+rsync
Linux系統實時資料同步inotify+rsync

   提示:到此我們就實作了把用戶端的指定目錄下的資源通過inotify監控和rsync實時的把資料同步到rysnc伺服器上。監控的事件我們可以在腳本裡用inotifywait -e去指定即可;我們發現腳本運作,它是前端運作的,如果我們把CRT視窗關閉了,随之我們的監控也失效了,是以我們希望腳本背景運作

  腳本以背景方式運作

[root@test-centos6-node1 ~]# bash inotify_rsync.sh &
[1] 1697
[root@test-centos6-node1 ~]# 
      
Linux系統實時資料同步inotify+rsync

   提示:我們把腳本以背景方式執行也是可以正常的把用戶端指定目錄下的檔案同步rsync伺服器上,到此inotify+rsync實作實時資料同步就完成了。

作者:Linux-1874

出處:https://www.cnblogs.com/qiuhom-1874/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利.

繼續閱讀