Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/home/juvenal/.pythonenv/bin/python
- import pyinotify
- import asyncore
- import os, sys, time
- import paramiko
- import pathutils
- import yaml
- class EventHandler(pyinotify.ProcessEvent):
- def process_IN_CLOSE_WRITE(self, event):
- filename = event.name
- filepath = event.path
- fullpath = event.pathname
- print "Closed:", event.pathname
- remote_path = Remote_Path_From_Local_Path(fullpath)
- #open SSH
- ssh = SSH_Connect(ActiveConfig.host,ActiveConfig.user,port=ActiveConfig.port)
- if not ssh:
- print "Aborting, no SSH Connection!"
- return False
- #create remote directory for file transfer
- if not SSH_Create_Directory(ssh, os.path.dirname(remote_path), parent=True):
- print "Aboring, failed to create remote directory!"
- return False
- #send file
- if not SSH_Send_File(ssh, fullpath, remote_path):
- print "Aborting, file failed to transfer!"
- return False
- print "Done! %s transfered to %s sucessfully!" % (filename, ActiveConfig.host)
- ssh.close()
- #remote_path = os.path.relpath(os.path.dirname(event.pathname), os.path.expanduser('~/Downloads'))
- #cmd = "rsync -vrzh --progress --chmod=Dugo+rx,u+wr,g+wr,o+r -e 'ssh -p 222' '%s' titansync@hs.juvsoft.com:'\"%s/\"'" % (event.pathname, remote_path)
- #args = shlex.split(cmd)
- #print args
- #subprocess.Popen(shlex.split("ssh -p 222 titansync@hs.juvsoft.com mkdir -p '\"%s\"'" % (remote_path,)), stdout=os.sys.stdout)
- #p = subprocess.Popen(args, stdout=os.sys.stdout, stderr=os.sys.stderr)
- def SSH_Connect(host, user, port=22, password=None):
- ssh = paramiko.SSHClient()
- ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
- ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
- try:
- ssh.connect(host, username=user, port=port, password=password)
- except paramiko.AuthenticationException:
- print "Could not login to remote server, please check your keys!"
- return False
- except:
- print "Could not connect to remote server, unknown reason!"
- return False
- return ssh
- def SSH_Create_Directory(SSHClient, directory, parent=False):
- pstr = ''
- if parent: pstr='--parents'
- command = "mkdir -v %s '%s'" % (pstr, directory)
- stdin, stdout, stderr = SSHClient.exec_command(command)
- s_out = stdout.readlines()
- s_err = stderr.readlines()
- if s_err:
- print "Error creating directory:"
- for l in s_err:
- print l
- return False
- if s_out:
- for l in s_out:
- print l
- return True
- if not s_out and not s_err:
- print "Nothing returned!"
- return False
- def SSH_Send_File(SSHClient, localpath, remotepath, callback=None):
- _start_time = [time.time()]
- def _callback(done, total):
- t = time.time()
- t = (t-_start_time[0])
- prog = '%s of %s - %i%s - %s/s' % (pathutils.formatbytes(done),pathutils.formatbytes(total), (done * 100)/total, "%", pathutils.formatbytes(done/t))
- print prog, ' ', '\r',
- sys.stdout.flush()
- if not callback:
- callback = _callback
- try:
- sftp = SSHClient.open_sftp()
- sftp.put(localpath, remotepath, callback)
- return True
- except:
- print "Unknown Error while sending file via sftp"
- return False
- def Remote_Path_From_Local_Path(local_path):
- head = local_path
- tail = ' '
- while tail is not '':
- head,tail = os.path.split(head)
- #print head, tail
- for Dir in ActiveConfig.Dirs:
- if os.path.samefile(Dir.local_path, head):
- return os.path.join(Dir.remote_path, os.path.relpath(local_path, head))
- class ScanDir(object):
- def __init__(self, name, conf_dict):
- self.name = name
- self.local_path = ''
- self.auto_add = False
- self.recursive = False
- self.remote_path = ''
- for attr in ('local_path','remote_path'):
- if not attr in conf_dict:
- print "Config Error! %s ScanDir does not have required attribute %s" % (self.name, attr)
- return
- setattr(self, attr, conf_dict[attr])
- for attr in ('auto_add', 'recursive'):
- if attr in conf_dict:
- setattr(self, attr, conf_dict[attr])
- self.local_path = os.path.expanduser(self.local_path)
- def __repr__(self):
- return "<ScanDir %s Local:%s Remote:%s R:%s A:%s>" % (self.name, self.local_path, self.remote_path, self.recursive, self.auto_add)
- class ActiveConfig(object):
- Dirs=[]
- WD={}
- mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_CREATE
- wm = pyinotify.WatchManager()
- notifier = pyinotify.AsyncNotifier(wm, EventHandler())
- def ParseConfig(filename):
- config = yaml.load(open(filename, 'r'))
- for attr in ('directories', 'remote_host'):
- if not attr in config:
- print "Config Error! %s is missing from root of config file %, it is required!" % (attr, filename)
- return False
- if not isinstance(config[attr], dict):
- print "Config Error! %s is not of the correct type! %s" % (attr, filename)
- return False
- dirlist = config['directories']
- remote_host = config['remote_host']
- for dirname, dirconf in dirlist.iteritems():
- d = ScanDir(dirname, dirconf)
- ActiveConfig.Dirs.append(d)
- for attr in ('host', 'user'):
- if not attr in remote_host:
- print "Config Error! %s is missing from remote_host section in %s" % (attr, filename)
- return False
- for key, val in remote_host.iteritems():
- setattr(ActiveConfig, key, val)
- def AddWatches():
- for SDir in ActiveConfig.Dirs:
- if not os.path.isdir(SDir.local_path):
- print "Path specified in %s not found! %s" % (SDir.name, SDir.local_path)
- return False
- wdd = ActiveConfig.wm.add_watch(SDir.local_path, ActiveConfig.mask, rec=SDir.recursive, auto_add=SDir.auto_add)
- return True
- if __name__ == "__main__":
- ParseConfig('config.yml')
- AddWatches()
- asyncore.loop()
Add Comment
Please, Sign In to add comment