Linux – Use inotifywait and lftp to synchronize servers

bashftpinotifylinux

I have two servers:

  • Server A (CentOS), where people can upload files to (upload root is /files)
  • Server B (Win 2008), with FileZilla FTP Server (FTP root is C:\content)

I want that whenever a file is uploaded to Server A, to any subfolder under /files, the file is automatically copied to the exact same subfolder on Server B. Thus, if a user uploads "flowers.jpg" to /files/photos/12345/ then the file must be copied over FTP to C:\content\photos\12345

So far I have this bash script, it does copy the files to server B, but all files are placed in C:\content, and not in the corresponding subfolders. Who can help me find the correct syntax?

#!/bin/bash
cd /files

inotifywait -q -r -m -e close_write,moved_to . --format %w%f | 
  while read FILE; do
    lftp -e "put $FILE; exit" -u user,password -p 2121 ftp.server-a.com
  done

Best Answer

That's because the FTP command put $FILE will put the file $FILE into whatever the 'current directory' is in the FTP Server side; hence, into the root directory of the FTP Server (which is located in C:\content).

You need to first extract the subdirectory from inotifywait's %w output, then prepend a cd FTP command to the lftp parameter.

I have never used inotifywait before, but I think the script should be like this:

inotifywait -q -r -m -e close_write,moved_to . --format "%w %f" | 
  while read DIR FILE; do
    lftp -e "cd $DIR; put $FILE; exit" -u user,password -p 2121 ftp.server-a.com
  done

PS: It's never a good idea to explicitly write a password in a script. Use rsync instead; on Windows, you'll need to install an rsync server. I personally use Cygwin, and use cygrunsrv to make rsync run as a Windows service.