读取用 Python Paramiko SFTPClient.open 方法打开的文件很慢

Reading file opened with Python Paramiko SFTPClient.open method is slow

我正在尝试远程读取 netcdf 文件。
我使用 Paramiko 包来读取我的文件,如下所示:

import paramiko
from netCDF4 import Dataset

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=’hostname’, username=’usrname’, password=’mypassword’)

sftp_client = client.open_sftp()
ncfile = sftp_client.open('mynetCDFfile')
b_ncfile = ncfile.read()    # ****

nc = Dataset('test.nc', memory=b_ncfile)

但是ncfile.read()的运行速度非常慢。

所以我的问题是:有没有其他方法可以远程读取 netcdf 文件,或者有什么方法可以加快速度 paramiko.sftp_file.SFTPFile.read()

调用SFTPFile.prefetch应该会提高读取速度:

ncfile = sftp_client.open('mynetCDFfile')
ncfile.prefetch()
b_ncfile = ncfile.read()

另一个选项是启用读取缓冲,使用 SFTPClient.openbufsize 参数:

ncfile = sftp_client.open('mynetCDFfile', bufsize=32768)
b_ncfile = ncfile.read()

(32768SFTPFile.MAX_REQUEST_SIZE的一个值)

与 writes/uploads 类似:
Writing to a file on SFTP server opened using pysftp "open" method is slow.


另一种选择是明确指定要读取的数据量(这使得 BufferedFile.read 采用更高效的代码路径):

ncfile = sftp_client.open('mynetCDFfile')
b_ncfile = ncfile.read(ncfile.stat().st_size)

如果 none 有效,您可以将整个文件下载到内存中:


强制性警告:请勿以这种方式使用 AutoAddPolicy – 您正在失去针对 MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

的保护