public
Created

Python snippet for uploading file to another server

  • Download Gist
uploader.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
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()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.