Read a file from server with SSH using Python Read a file from server with SSH using Python python python

Read a file from server with SSH using Python


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 linefinally:    remote_file.close()


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

from fabric.connection import Connectionwith 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 closingfrom fabric.network import connectwith 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)


#!/usr/bin/env pythonimport paramikoimport selectclient = 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)