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)
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)
看起来早在 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)
#!/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)