我使用paramiko在python中打开远程sftp文件。使用paramiko返回的文件对象,我正在逐行读取文件并处理信息。与在操作系统中使用python内置方法"open"相比,这似乎真的很慢。下面是我用来获取文件对象的代码。
使用paramiko(慢2倍)-
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(myHost,myPort,myUser,myPassword)
sftp = client.open_sftp()
fileObject = sftp.file(fullFilePath,'rb')
使用os -
import os
fileObject = open(fullFilePath,'rb')
我错过什么了吗?是否有一种方法可以使paramiko文件对象读取方法与使用os文件对象的方法一样快?
谢谢! !
您的问题很可能是由于文件是远程对象引起的。您已经在服务器上打开了它,并且每次请求一行—因为它不是本地的,每次请求所花费的时间比文件放在硬盘驱动器上要长得多。最好的替代方法可能是首先将文件复制到本地位置,使用Paramiko的SFTP get
。
完成后,您可以使用os.open
从本地位置打开该文件。
我遇到了同样的问题,由于安全原因我无法在本地复制文件,我通过使用预取和bytesIO的组合来解决这个问题:
def fetch_file_as_bytesIO(sftp, path):
"""
Using the sftp client it retrieves the file on the given path by using pre fetching.
:param sftp: the sftp client
:param path: path of the file to retrieve
:return: bytesIO with the file content
"""
with sftp.file(path, mode='rb') as file:
file_size = file.stat().st_size
file.prefetch(file_size)
file.set_pipelined()
return io.BytesIO(file.read(file_size))
这是一种使用在paramiko中抓取命令行(cat)并一次读取所有行的方法。
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect(hostname=host, port=port, username=user, key_filename=ssh_file)
stdin, stdout, stderr = client.exec_command('cat /proc/net/dev')
net_dump = stdout.readlines()
#your entire file is now in net_dump .. do as you wish with it below ...
client.close()
我打开的文件非常小,所以这完全取决于你的文件大小。值得一试