在python s中使用paramiko打开远程文件

2024-05-14 16:14:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用paramiko在python中打开一个远程sftp文件。使用paramiko返回的file对象,我逐行读取文件并处理信息。与在操作系统中使用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')

使用操作系统-

import os
fileObject = open(fullFilePath,'rb')

我有什么遗漏吗?有没有办法使paramiko fileobject的读取方法与使用os fileobject的方法一样快?

谢谢!!


Tags: 文件对象方法clienthostparamiko远程os
3条回答

您的问题可能是由于文件是远程对象造成的。您已经在服务器上打开了它,并且一次只请求一行,因为它不是本地的,所以每个请求所需的时间都比文件放在硬盘上的时间要长得多。最好的替代方法可能是首先使用Paramiko的^{}将文件复制到本地位置。

完成后,可以使用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()

我打开的文件很小,所以这取决于你的文件大小。值得一试:)

相关问题 更多 >

    热门问题