Automatic Backup to FTP with fsniper and lftp

In this article I will show you an easy and comfortable way to synchronize a specific directory to a ftp-server automatically whenever the contents of the directory change.

Necesarry Tools

As you can see in the headline of this article we will use fsniper for monitoring file changes and lftp to do the uploading. On gentoo the installation is as simple as

emerge fsniper lftp

(maybe you will have to add fsniper to package.keywords). Note that for fsinper to work you will need a kernel with enabled inotify-support (most distribution-kernels will have this on by default).

The Upload Script

First we will write a little script that does the uploading to the ftp-server for us. Here it is:

#!/bin/bash

trap "rm /tmp/ftpsync.lock" SIGINT SIGTERM

if [ -e /tmp/ftpsync.lock ]
then
  echo "ftpsync already running.."
  exit 2
else
  touch /tmp/ftpsync.lock
  lftp your.ftp.server -u yourFtpUser,yourPassword << EOF # replace your.ftp.server, yourFtpUser and yourPassword with the correct values
lcd /FtpSync # Replace /FtpSync with the local directory you want to backup
mirror -R -e
quit
EOF
  rm /tmp/ftpsync.lock
  exit 0
fi

Put this into .config/fsniper/scripts/ftpsync.sh in the users directory who runs fsniper (you may have to create the directories manually) and make it executable. Note: This script will backup to the root directory of your ftp-account, if you want to backup to a specific subdirectory, simply add

cd DirectoryYouWantToBackupTo

after the

lcd /FtpSync

line in the script.

Thats all for the script, now on to the fsniper config

Configuring fsniper

Last step for the setup is to configure fsniper. The config is in .config/fsniper/config and should look like this:

delay_time = 600 
delay_repeats = 0

watch {
  /FtpSync {
    recurse = true
    * {
      handler = ftpsync.sh
    }
  }
}

Some explanation:
delay_time = 600 is the time to wait between retries (in seconds) when the script reports that it is already running
delay_repeats = 0 means to retry infinite times, to ensure everything is correctly synced, even if many files ar added at the same time (fsniper activates the script per changed file)
/FtpSync is again the directory you want to Backup, should be the same as in the script above

Final Touch

Now we have all things in place, you just have to start fsniper and it will work. Simply add

fsniper --daemon

somewhere to your users startup scripts (~/.bashrc or the session-configuration of your desktop environment for example).

Thats it. If you have questions or suggestions, feel free to leave a comment below.

blog/automatic_backup_to_ftp_with_fsniper_and_lftp.txt · Last modified: 28.09.2010 13:39 by Seiichiro
CC Attribution-Share Alike 3.0 Unported
Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0