在 Flask 中提供使用 Paramiko SFTP 下载的文件
Serve file downloaded with Paramiko SFTP in Flask
我编写了一个 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
如果数据太大,请使用 SFTPClient.getfo
to copy a file from the remote path, then send a response with the data. Use a 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
.
,则会出现安全问题
我编写了一个 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
如果数据太大,请使用 SFTPClient.getfo
to copy a file from the remote path, then send a response with the data. Use a 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
.