Chinaunix首页 | 论坛 | 博客
  • 博客访问: 84498
  • 博文数量: 25
  • 博客积分: 1435
  • 博客等级: 上尉
  • 技术积分: 152
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-09 17:12
个人简介

fsdfas

文章分类

全部博文(25)

文章存档

2014年(1)

2013年(24)

我的朋友

分类: 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

server = sftp.Server("user""pass""example.com")
# upload a file
server.upload("/local/path""/remote/path")
# download a file
server.download("remote/path""/local/path")
server.close()

with statement also supported:

with sftp.Server("user""pass""example.com") as server:
    server.upload("/local/path""/remote/path")

Finally, a demo recipe for uploading all the png files from a specified local directory to a specified directory on the server:

# needed for python 2.5
from __future__ import with_statement


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:

import paramiko


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__(selftype, value, tb):
        self.close()

阅读(533) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~