使用python通过sftp上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33751854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:55:10  来源:igfitidea点击:

Upload file via sftp with python

pythonpython-2.7sftppysftp

提问by user781486

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

我写了一个简单的代码将文件上传到python中的sftp服务器。我正在使用 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.

编辑:我已启用日志记录。我发现文件上传到根文件夹而不是公共文件夹下。好像没用srv.cd('public')

采纳答案by user781486

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.putinside with srv.cd

srv.put里面放srv.cd

回答by Amit Ghosh

import pysftp

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

  srv.cwd('/root/public'): #Write the whole path
  srv.put('C:\Users\XXX\Dropbox\test.txt') #upload file to nodejs/

No srv.close()as connection closed automatically at the end of the with-block

否,srv.close()因为在 with-block 结束时连接自动关闭

I did a minor change with cdto cwd

我做了一个小的改动cd,以cwd

Syntax -

句法 -

# sftp.put('/my/local/filename')  # upload file to public/ on remote
# sftp.get('remote_file')         # get a remote file