首页 > 解决方案 > SFTP 无法识别上传的文件

问题描述

我正在使用 pysftp 上传远程处理的本地文件,然后返回到 SFTP,我可以在那里下载它。目前,我无法让代码识别已处理的远程文件已上传。尽管远程处理的文件已成功上传,但代码只会永远等待。

在代码运行时,如果我在 FileZilla 等服务上刷新连接,代码会立即识别出文件在其中并且运行良好。但是,我需要它在不手动刷新 FileZilla 的情况下工作。我不确定为什么代码无法识别文件已上传并可以下载。

我已经尝试使用 while 语句断开连接然后重新连接到 SFTP,但没有成功。

import pysftp
import stat

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
srv = pysftp.Connection(host="host", username="username", password="passowrd", cnopts=cnopts)

print("Connection Made!")

# Put File In
srv.chdir(r'/path_to_remote_directory')

srv.put(r'C:\Path_to_local_file.csv')
print("File Uploaded")

while not srv.isfile(r'/Path_to_newly_uploaded_remote_file.csv'):
    time.sleep(3)
    print("Still Waiting")

if srv.isfile(r'/Path_to_newly_uploaded_remote_file.csv'):
    print("File is Ready!")
    srv.get('/Path_to_newly_uploaded_remote_file.csv', r'C:\Local_path_save_to/file.csv')

    # Closes the connection
    srv.close()

标签: pythonsftppysftp

解决方案


只需删除/

srv.isfile(r'/Path_to_newly_uploaded_remote_file.csv'):
->
srv.isfile(r'Path_to_newly_uploaded_remote_file.csv'):

笔记:

不要设置 cnopts.hostkeys = None,除非你不关心安全性。这样做会失去对中间人攻击的保护。

我已经auto_add_key在我的pysftp github fork中实现了。

auto_add_key将把密钥添加到known_hosts如果auto_add_key=True
一旦密钥存在于known_hosts该密钥中的主机将被检查。

请参阅Martin Prikryl ->关于安全问题的回答。

为什么使用上下文管理器是一个好方法

import pysftp
with pysftp.Connection(host, username="whatever", password="whatever", auto_add_key=True) as sftp:
    #do your stuff here
#connection closed

编辑: 检查了我的代码,/是问题所在......请检查文件的拼写,并且您在正确的工作目录中getcwd()_

import pysftp
import stat
import time

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None #do not do this !!!
srv = pysftp.Connection("host", username="user", password="pass", cnopts=cnopts)

print("Connection Made!")

# Put File In
srv.chdir(r'/upload')

srv.put(r'C:\Users\Fabian\Desktop\SFTP\testcsv.csv')
print("File Uploaded")

print(srv.getcwd()) #get the current folder ! <- you should looking here

while not srv.isfile(r'testcsv.csv'):
    time.sleep(3)
    print("Still Waiting")

if srv.isfile(r'testcsv.csv'):
    print("File is Ready!")
    srv.get('testcsv.csv', r'C:\Users\Fabian\Desktop\SFTP\testcsv_new.csv')

    # Closes the connection
    srv.close()

推荐阅读