Read a file from server with SSH using Python

前端 未结 5 1133
北恋
北恋 2020-11-28 05:11

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

5条回答
  •  一生所求
    2020-11-28 05:49

    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)
    

提交回复
热议问题