需要在机器A与机器B之间实时同步文件,由于实时要求,rsync+crontab的方式就不符合条件了;在google上搜到inotify可以实时检测特定目录下文件的变动,但是需要复杂的配置,看到python的pyinotify库,正好练下python.

安装

pip install pyinotify

realtime_rsync.py

#!/usr/bin/python
#-*-coding:utf8-*-
import os
import subprocess
import pyinotify

sourcePath = '/home/yjiang/foo/'
targetPath = 'yjiang@yjiang.tk:/home/yjiang/bar/'

wm = pyinotify.WatchManager()

class rsync():
    def __init__(self, type, path):
        cmd = 'rsync -avz --delete %s %s' %(sourcePath, targetPath)
        subprocess.call(cmd, shell=True)
        print "%s: %s" % (type, path)

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        rsync('create', event.pathname)
    def process_IN_DELETE(self, event):
        rsync('delete', event.pathname)
    def process_IN_MODIFY(self, event):
        rsync('modify', event.pathname)

notifier = pyinotify.Notifier(wm, EventHandler())
wm.add_watch(sourcePath, pyinotify.ALL_EVENTS, rec=True)    #rec=True sub-dir support
notifier.loop()