Ashish Verma
Ashish Verma

Reputation: 21

File upload to SFTP using Python (pysftp) fails with "No such file"

I am trying to upload a CSV file to an SFTP server from my machine. I don't know why my code is not able to find the file. Need little help to identify the issue. Here's my code

import pysftp as sftp
def sftpExample():
    try:
        cnopts = sftp.CnOpts()
        cnopts.hostkeys = None
        s = sftp.Connection(host='abc.net', username='xyz', password='aaaaaaaaaaaa',cnopts=cnopts)

        remotepath = 'http://sftp.abc.net/uploads/'
        localpath = '/Users/ashish.verma/Desktop/Text.rtf'
        s.put(localpath,remotepath)

        s.close()

    except Exception as e:
        print(e)
sftpExample()

Connection to the SFTP server is successful, but I don't know why my code is not able to find the file on my local machine. Error message says:

No such file

Upvotes: 1

Views: 2628

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202652

The remotepath argument of pysftp Connection.put method is a file path. Not directory URL, let alone HTTP URL.

It should be like:

remotepath = '/uploads/Text.rtf'
s.put(localpath, remotepath)

Alternatively you can omit the argument, making pysftp upload the file to the current remote working directory under the original file name (taken from localpath):

s.cd('/uploads')
s.put(localpath)

Obligatory warning: Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp.

Upvotes: 2

Related Questions