I used paramiko for a project a while ago and wrote the following, called sftp_wrapper.py, to help with things:
'''
sftp_wrapper.py is a wrapper class for the sftp portion of the
paramiko library.
'''
import paramiko
class Session(object):
def __init__(self, hostname, username, password):
self.tunnel = paramiko.Transport((hostname, 22))
hostkeys = paramiko.util.load_host_keys('known_hosts')
hostkey = hostkeys[hostname]['ssh-rsa']
self.tunnel.connect(username=username, password=password,
hostkey=hostkey)
self.sftp = paramiko.SFTPClient.from_transport(self.tunnel)
def open(self, filename, mode='r'):
return self.sftp.open(filename, mode=mode)
def chdir(self, dir):
self.sftp.chdir(dir)
def get(self, remote, local=None):
if not local:
local = remote
self.sftp.get(remote, local)
def put(self, local, remote=None):
if not remote:
remote = local
self.sftp.put(local, remote)
def listdir(self, remote):
return self.sftp.listdir(remote)
def remove(self, remote):
self.sftp.remove(remote)
def close(self):
self.tunnel.close()