Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file from server with SSH using Python

I am trying to read a file from a server using SSH from Python. I am using Paramiko to connect. I can connect to the server and run a command like cat filename and get the data back from the server but some files I am trying to read are around 1 GB or more in size.

How can I read the file on the server line by line using Python?

Additional Info: What is regularly do is run a cat filename command and store the result in a variable and work off that. But since the file here is quite big, I am looking for a way to read a file line by line off the server.

EDIT: I can read a bunch of data and split it into lines but the problem is that the data received in the buffer does not always include the complete lines. For eg, if buffer has 300 lines, the last line may only be half of the line on the server and the next half would be fetched in the next call to the server. I want complete lines

EDIT 2: what command can I use to print lines in a file in a certain range. Like print first 100 lines, then the next 100 and so on? This way the buffer will always contain complete lines.

like image 396
randomThought Avatar asked Oct 20 '09 20:10

randomThought


2 Answers

Paramiko's SFTPClient class allows you to get a file-like object to read data from a remote file in a Pythonic way.

Assuming you have an open 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() 
like image 99
Matt Good Avatar answered Sep 21 '22 21:09

Matt Good


Here's an extension to @Matt Good's answer, using fabric:

from fabric.connection import Connection  with Connection(host, user) as c, c.sftp() as sftp,   \          sftp.open('remote_filename') as file:     for line in file:         process(line) 

old Fabric 1 answer:

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) 
like image 41
jfs Avatar answered Sep 25 '22 21:09

jfs