This recipe shows how to setup a basic synchronization mechanism (similar to DropBox) by means of conventional GNU/Linux tools. This does not require root privileges and no packages (except ssh-server) need to be installed in the server.

WARNING: This procedure may cause data loss. Use it under your responsibility

Ingredients

In the client:

  • cron
  • incron

In the server:

  • ssh server

The server should be accessible from everywhere and configured for using ssh public key authentication. Nothing else needs to be modified in your server.

The “poorbox” script

Put that in your ~/bin/poorbox.sh:

#!/bin/bash --
# poorbox.sh {to-host|to-server} [file EVENT]

set -e

SERVER=server
USER=john
FOLDER=PoorBox/

LOCAL=/home/$USER/$FOLDER
REMOTE=$SERVER:$FOLDER

case $1 in
 "to-host")
	SOURCE=$REMOTE
	TARGET=$LOCAL
	;;
 "to-server")
	SOURCE=$LOCAL
	TARGET=$REMOTE
	;;
 * )
    echo "usage: $0 [to-host|to-server]"
	exit 1
esac

LOCK=/tmp/$USER.poorbox

# avoid reentrant execution
flock -n $LOCK-$1 true

if [ "$3" == "IN_DELETE" ]; then
	CMD="ssh $SERVER rm $FOLDER$2"
else
	CMD="rsync -avz --delete $SOURCE$2 $TARGET"
fi

# wait for the inverse transfer
flock $LOCK $CMD

Synchronizing host to server

The next configuration will copy or delete any modified file from your laptop/PC to your server account. First, you need to put your username in the /etc/incron.allow file.

Run that in a terminal:

$ incrontab -e

Your default editor will start. Write down next line, save and close.

/home/john/PoorBox IN_MODIFY,IN_DELETE,IN_CLOSE_WRITE,IN_MOVE /home/john/bin/poorbox.sh to-server $# $%

and then:

$ incrontab -d

Synchronizing host from server

We will not detect changes in server files (although may be possible using the same way). We will poll changes using cron. Run next in a console:

$ crontab -e

write and save next line:

*/1 *  *   *   *     /home/john/bin/poorbox.sh to-host

This poll each minute. Of course, you may increase or decrease the polling frequency as you prefer.

Improving performance

Continuous ssh connections does not seems a good idea, but it is possible tweak your config by means of ControlMaster and KeepAlive ssh options.

Limitations

Currently incron does not detect recursive events (operations on subdirectories)

References



blog comments powered by Disqus