Skip to content

Instantly share code, notes, and snippets.

@pcdinh
Forked from JordanReiter/uploader.py
Created September 9, 2012 18:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcdinh/3686370 to your computer and use it in GitHub Desktop.
Save pcdinh/3686370 to your computer and use it in GitHub Desktop.
Python snippet for uploading file to another server
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment