使用Paramiko SFTP在Flask中下载文件

时间:2015-08-05 13:23:01

标签: python flask sftp paramiko

我写了一个Flask应用程序,用Paramiko的SFTP支持浏览远程系统。我希望客户端能够在浏览时下载远程文件。如何使用Paramiko下载文件并使用Flask进行服务?

@app.route('/download/path:<path:to_file>/')
def download(to_file):
    ssh = paramiko.SSHClient()
    privatekeyfile = os.path.expanduser(key)
    mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, username=user, pkey=mykey)
    transfer = ssh.open_sftp()

    # what do I do here to get the file and serve it?
    download = transfer.~SOME_MAGIC~(to_file)
    return download

1 个答案:

答案 0 :(得分:2)

使用SFTPClient.getfo从远程路径复制文件,然后发送包含数据的响应。如果数据太大,请使用SpooledTemporaryFile将数据存储在内存或临时文件中。

import os
from tempfile import SpooledTemporaryFile
from flask import Flask
from paramiko import SSHClient

app = Flask(__name__)

@app.route('/remote_download/<path:path>')
def remote_download(path):
    client = SSHClient()
    client.connect('host')
    transfer = client.open_sftp()

    with SpooledTemporaryFile(1024000) as f:  # example max size before moving to file = 1MB
        transfer.getfo(path, f)
        f.seek(0)
        r = app.response_class(f.read(), mimetype='application/octet-stream')

    r.headers.set('Content-Disposition', 'attachment', filename=os.path.basename(path))
    return r

app.run()

您应该做一些事情来检查路径是否有效,否则如果路径类似于../sibling/path/secret.txt则会出现安全问题。