Skip to content

Instantly share code, notes, and snippets.

@taksatou
Created October 24, 2012 11:53
Show Gist options
  • Save taksatou/3945678 to your computer and use it in GitHub Desktop.
Save taksatou/3945678 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
import paramiko
import getpass
import traceback
class RemoteSyncHandler(LoggingEventHandler):
def __init__(self, *args, **kwargs):
super(RemoteSyncHandler, self).__init__()
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.host = raw_input('Host: ')
self.user = raw_input('User: ')
self.passwd = getpass.getpass('Pass: ')
self.src = kwargs['src']
self.dst = kwargs['dst']
self.ssh.connect(self.host, username=self.user, password=self.passwd)
self.sftp = self.ssh.open_sftp()
def on_modified(self, event):
super(RemoteSyncHandler, self).on_modified(event)
self.sync_file(event.src_path)
def on_created(self, event):
super(RemoteSyncHandler, self).on_created(event)
self.sync_file(event.src_path)
def mkdirs(self, path):
self.ssh.exec_command("mkdir -p %s" % path)
def sync_file(self, filepath):
try:
relpath = os.path.relpath(filepath, self.src)
target = self.dst + '/' + relpath
print '%s -> %s' % (filepath, target)
if not os.path.isdir(filepath):
self.mkdirs(os.path.dirname(target))
self.sftp.put(filepath, target)
else:
self.mkdirs(target)
except:
print traceback.format_exc()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
event_handler = RemoteSyncHandler(dst=sys.argv[2], src=sys.argv[1])
observer = Observer()
observer.schedule(event_handler, path=sys.argv[1], recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment