Srikanth Ponnapati
Srikanth Ponnapati

Reputation: 1

How can I download file from SFTP using pysftp?

I have a SFTP server that contains a set of folders. I would like to download a file from one of these folders.

Can someone help me with the python code?

Where should I start?

Upvotes: 0

Views: 5818

Answers (2)

Kevin Huang
Kevin Huang

Reputation: 71

An addition from Michael Powers.

If your server is one account and your personal account is another one. If your server account has root permission, then follow Michael's method. If no, you may use io buffer to download this file

    import io
    server_sftp = pysftp.Connection(host=test_host, username=server_account,
                              password=server_pwd, cnopts=cn_opts)
    your_user_sftp = pysftp.Connection(host=host_name, username = user_name,
                                password = user_pwd, cnopts=cn_opts)

    try:
        file_like=io.BytesIO()
        server_account.getfo(server_file_location,file_like)
        your_user_sftp.putfo(file_like, target_file_location)
    finally:
        flie_like.close()

    server_sftp.close()
    your_user_sftp.close()

Upvotes: 1

Michael Powers
Michael Powers

Reputation: 2050

Have you tried the example in pysftp's documentation?

import pysftp

with pysftp.Connection('hostname', username='me', password='secret') as sftp:
    with sftp.cd('public'):             # temporarily chdir to public
        sftp.put('/my/local/filename')  # upload file to public/ on remote
        sftp.get('remote_file')         # get a remote file

Upvotes: 1

Related Questions