I often work from home, and keep a not so up to date mirror of certain
dirs of my main remote server where I do most of my work.  I don't
want my /home at home to a perfect mirror of my /home at work, but for
some subdirs I do.  Here is a little python script that is an
interface to rsync that mirrors a remote subdir by looking at what
subdir you are in locally.

For example, if I am in ~/c/data locally, I just type 

  > mirror.py -d

to make the local ~/c/data/ a mirror of the remote ~/c/data/.  -d says
to remove local files if they are not on the remote server (a true
mirror).  Default is to keep local files.

rsync is nice because it only gets what is needed, works over ssh and
does compression.

Currently, this works only in /home and it's subdirectories.  I'll
probably improve it in the near future to work with file lists of dirs
to mirror and to extend it's reach beyond home, but for now, it's
simple and effective for an on-the-spot local mirror.

#!/usr/local/bin/python

import os, sys

deleteFlag = ''
if '-d' in sys.argv:
    deleteFlag = '--delete'

server = 'nitace'

homeDir = os.environ['HOME']
homeDir = homeDir + '/'
homeLen = len(homeDir)


thisDir = os.getcwd()
#expecting a '/' so add it if it's not there
if (thisDir[len(thisDir)-1] != '/'):
    thisDir = thisDir + '/'

#die if you are not in the home dir
if ( thisDir[0:homeLen] != homeDir):
    raise RuntimeError, \
          'current working dir %s does not match home dir %s' %\
          (thisDir, homeDir)

#all systems go, get the current path relative to home
relPath = thisDir[homeLen:]

#mirror the remote dir
mirror = 'rsync -avz %s -e ssh %s:%s .' % (deleteFlag, server, relPath)
print 'Executing:\n\t%s' % mirror
command = os.popen(mirror)
for line in command.readlines():
    print line.strip()

Reply via email to