21

I wrote a simple code to upload a file to a sftp server in python. I am using python 2.7

import pysftp

srv = pysftp.Connection(host="www.destination.com", username="root",
password="password",log="./temp/pysftp.log")

srv.cd('public') #chdir to public
srv.put('C:\Users\XXX\Dropbox\test.txt') #upload file to nodejs/

# Closes the connection
srv.close()

The file did not appear on the server. However, no error message appeared. What is wrong with the code?

EDIT: I have enabled logging. I discovered that the file is uploaded to the root folder and not under public folder. Seems like srv.cd('public') did not work.

guagay_wk
  • 23,870
  • 50
  • 164
  • 275
  • 1
    It's a bit hard to tell from your description. Set `log='/tmp/pysftp.log'` when creating the Connection and investigate the log file. – Frederick Nord Nov 17 '15 at 08:09

3 Answers3

39

I found the answer to my own question.

import pysftp

srv = pysftp.Connection(host="www.destination.com", username="root",
password="password",log="./temp/pysftp.log")

with srv.cd('public'): #chdir to public
    srv.put('C:\Users\XXX\Dropbox\test.txt') #upload file to nodejs/

# Closes the connection
srv.close()

Put the srv.put inside with srv.cd

guagay_wk
  • 23,870
  • 50
  • 164
  • 275
8
import pysftp

with pysftp.Connection(host="www.destination.com", username="root",
password="password",log="./temp/pysftp.log") as sftp:

  sftp.cwd('/root/public')  # The full path
  sftp.put('C:\Users\XXX\Dropbox\test.txt')  # Upload the file

No sftp.close() is needed, because the connection is closed automatically at the end of the with-block

I did a minor change with cd to cwd

Syntax -

# sftp.put('/my/local/filename')  # upload file to public/ on remote
# sftp.get('remote_file')         # get a remote file
Ilja Leiko
  • 426
  • 1
  • 7
  • 22
Amit Ghosh
  • 1,368
  • 11
  • 17
0

With as a context manager will close the connection. Explicitly using srv.close() is not required

Ambesh
  • 51
  • 7