fsdfas
分类: Python/Ruby
2013-04-10 12:20:20
本文转自:
makes it so easy to use SFTP that it's hard to believe it's legal in this day and age. has a wonderful post showing .
In this post, I want to share a small helper module called (code in post below) that wraps paramiko.SFTPClient and makes uploading/downloading via SFTP even simpler.
First, some usage
Upload or download a file
with statement also supported:
Finally, a demo recipe for uploading all the png files from a specified local directory to a specified directory on the server:
import sftp
import glob
from os import path
remote_dir = "/path/on/remote/server/"
with sftp.Server("user", "pass", "") as server:
for image in glob.glob("/local/path/to/*.png"):
base = path.basename(image)
server.upload(image, path.join(remote_dir, base))
Now, here's the code for my sftp module:
class Server(object):
"""
Wraps paramiko for super-simple SFTP uploading and downloading.
"""
def __init__(self, username, password, host, port=22):
self.transport = paramiko.Transport((host, port))
self.transport.connect(username=username, password=password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
def upload(self, local, remote):
self.sftp.put(local, remote)
def download(self, remote, local):
self.sftp.get(remote, local)
def close(self):
"""
Close the connection if it's active
"""
if self.transport.is_active():
self.sftp.close()
self.transport.close()
# with-statement support
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.close()