从服务器读取一个文件使用Python SSH(Read a file from server wit

2019-08-22 07:17发布

我想读使用SSH从Python中的服务器上的文件。 我使用的paramiko连接。 我可以连接到服务器并运行这样的命令cat filename和获取数据从服务器,但一些文件,我想读回为中心在尺寸1 GB或更多。

我怎样才能读取使用Python一行服务器行的文件?

附加信息:什么是定期做的是运行一个cat filename的命令,并将结果存储在变量和关闭工作。 但由于这里的文件是相当大的,我正在寻找一种方式来读取文件里逐行关闭服务器。

编辑:我可以读一组数据,并将其分割成线,但问题是,在缓冲区接收到的数据并不总是包含完整的生产线。 对于例如,如果缓冲区有300行,最后一行可能只有一半的线的服务器上,下半将在服务器下一次调用获取。 我想整线

编辑2:我可以在一定范围内使用的命令行打印在一个文件中。 像打印头100线,那么接下来的100等等? 这样,缓冲区将总是包含完整的生产线。

Answer 1:

的paramiko的SFTPClient类可以让你得到一个类文件对象的Python化的方式从远程文件读取数据。

假设你有一个开放的SSHClient

sftp_client = ssh_client.open_sftp()
remote_file = sftp_client.open('remote_filename')
try:
    for line in remote_file:
        # process line
finally:
    remote_file.close()


Answer 2:

下面是一个扩展@马特良好的答案 :

from contextlib     import closing
from fabric.network import connect

with closing(connect(user, host, port)) as ssh, \
     closing(ssh.open_sftp()) as sftp, \
     closing(sftp.open('remote_filename')) as file:
    for line in file:
        process(line)


Answer 3:

你是什​​么意思“逐行” - 有大量的网络主机之间的数据缓冲区,和他们都不是面向行的。

所以,你可以读出一组数据,那么它在近端分割成线。

ssh otherhost cat somefile | python process_standard_input.py | do_process_locally

或者你可以有一个过程在远端读取一组数据,打破它,和逐行格式,并将其发送给您。

scp process_standard_input.py otherhost
ssh otherhost python process_standard_input.py somefile |  do_process_locally

我会关心的唯一区别是什么样的方式减少数据在有限的网络管道的容量。 在您的情况可能或可能并不重要。

有没有错,一般用cat通过SSH管道移动千兆字节的数据。



Answer 4:

#!/usr/bin/env python
import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('yourhost.com')
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command("cat /path/to/your/file")
while True:
  rl, wl, xl = select.select([channel],[],[],0.0)
  if len(rl) > 0:
      # Must be stdout
      print channel.recv(1024)


文章来源: Read a file from server with SSH using Python