Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import errno
- import os
- import paramiko
- class Uploader(object):
- def __init__(self, host, basepath='', username=None, password=None, keyfile=None, *args, **kwargs):
- self.host = host
- self.basepath = basepath
- self.username = username
- self.password = password
- self.keyfile = keyfile
- self.currentpath = self.basepath
- super(Uploader, self).__init__(*args, **kwargs)
- self.setup()
- def cwd(self):
- return self.currentpath
- def cd(self, path=''):
- if path and path[0] == '/':
- newpath = os.path.abspath(os.path.join(self.basepath, path))
- else:
- newpath = os.path.abspath(os.path.join(self.currentpath, path))
- self.sftp.lstat(newpath)
- self.currentpath = os.path.join(newpath)
- return newpath
- def setup(self):
- self.ssh = paramiko.SSHClient()
- self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh_kwargs = {}
- if self.username:
- ssh_kwargs['username'] = self.username
- if self.password:
- ssh_kwargs['password'] = self.password
- if self.keyfile:
- ssh_kwargs['key_filename'] = self.keyfile
- self.ssh.connect(self.host, **ssh_kwargs)
- self.sftp = self.ssh.open_sftp()
- def mkdir(self, path, recursive=True):
- try:
- self.sftp.mkdir(os.path.join(self.basepath, path))
- except IOError, inst:
- if getattr(inst,'errno') == errno.ENOENT and recursive:
- pathdirs = path.split(os.path.sep)
- for pp in range(1,len(pathdirs)):
- currentpath = os.path.join(self.basepath, *pathdirs[:pp+1])
- try:
- self.ftp.lstat(currentpath)
- except IOError, inst:
- if getattr(inst,'errno') == errno.ENOENT:
- self.sftp.mkdir(currentpath)
- else:
- raise
- else:
- raise
- return path
- def upload(self, sourcefile, path=None, destname=None, overwrite=False):
- """
- sourcefile can be a filepath or a file object
- so long as the file object has a value for name
- """
- try:
- filename = sourcefile.name
- except AttributeError:
- filename = sourcefile
- if not destname:
- _, destname = os.path.split(filename)
- if path == None:
- path = self.currentpath
- else:
- path = os.path.join(self.basepath, path)
- destpath = os.path.join(path, destname)
- filename_prefix, filename_ext = os.path.splitext(destpath)
- counter = 0
- while True:
- try:
- exists = self.sftp.lstat(destpath)
- if overwrite:
- print "Filename found, but because overwrite is true I will overwrite it."
- break
- counter += 1
- destpath = "%s_%d%s" % (filename_prefix, counter, filename_ext)
- print "Filename found, will try %s" % destpath
- except:
- break
- print "Uploading %s to %s" % (filename, destpath)
- self.sftp.put(filename, destpath)
- return destpath
- def finish(self):
- self.sftp.close()
- self.ssh.close()
Add Comment
Please, Sign In to add comment