在Python中使用paramiko打开远程文件慢

5 投票
3 回答
19658 浏览
提问于 2025-04-17 03:09

我在用paramiko这个库在Python中打开一个远程的sftp文件。通过paramiko返回的文件对象,我一行一行地读取文件内容并处理信息。这样做的速度比用Python自带的os库里的'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的文件读取速度一样快呢?

谢谢!!

3 个回答

3

这里有一种方法,可以通过在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()

我打开的文件都比较小,所以这主要取决于你的文件大小。值得一试哦 :)

5

我之前也遇到过同样的问题,由于安全原因,我不能把文件复制到本地。于是我用了一种方法,结合了预取和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))
7

你的问题可能是因为文件是一个远程对象。你在服务器上打开了这个文件,并且是逐行请求的——因为这个文件不在你的电脑上,所以每次请求的时间比如果文件在你硬盘上要长得多。最好的解决办法可能是先把文件复制到本地,使用Paramiko的SFTP get

完成这个步骤后,你就可以使用os.open从本地位置打开这个文件了。

撰写回答