使用python使用ssh从服务器读取文件

ran*_*ght 31 python ssh paramiko

我正在尝试使用python中的ssh从服务器读取文件.我正在使用paramiko进行连接.我可以连接到服务器并运行像'cat filename'这样的命令并从服务器获取数据,但我尝试读取的一些文件大小约为1 GB或更多.

如何使用python逐行读取服务器上的文件?

附加信息:经常做的是运行'cat filename'命令并将结果存储在变量中并解决该问题.但由于这里的文件非常大,我正在寻找一种逐行读取文件的方法.

编辑:我可以读取一堆数据并将其拆分成行,但问题是缓冲区中接收的数据并不总是包含完整的行.例如,如果缓冲区有300行,则最后一行可能只是服务器上行的一半,下一半将在下次调用服务器时获取.我想要完整的线条

编辑2:我可以使用什么命令在特定范围内的文件中打印行.喜欢打印前100行,那么接下来的100行等等?这样缓冲区将始终包含完整的行.

Mat*_*ood 57

Paramiko的 SFTPClient类允许您获得类似文件的对象,以Pythonic方式从远程文件中读取数据.

假设你有一个开放的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()
Run Code Online (Sandbox Code Playgroud)

  • +1,比麻烦猫更好(对于我喜欢的所有猫科动物! - ). (7认同)
  • 虽然正确,但这种简单的实现速度非常慢。它需要一些改进才能获得良好的性能。请参阅[读取使用Python Paramiko SFTPClient.open方法打开的文件很慢](/sf/ask/4090379751/)。 (5认同)

jfs*_*jfs 10

这是@Matt Good的答案的扩展:

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)
Run Code Online (Sandbox Code Playgroud)


sql*_*vel 6

看起来早在 2013 年 9 月,paramiko 就添加了这些对象本身支持上下文管理器的能力,因此,如果您想要Matt 的干净答案jfs 的上下文管理器,现在您需要的是:

with ssh_client.open_sftp() as sftp_client:
    with sftp_client.open('remote_filename') as remote_file:
        for line in remote_file:
            # process line
Run Code Online (Sandbox Code Playgroud)


g33*_*z0r 5

#!/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)
Run Code Online (Sandbox Code Playgroud)