gpt4 book ai didi

python - SFTP 无法识别上传的文件

转载 作者:行者123 更新时间:2023-12-01 07:20:42 25 4
gpt4 key购买 nike

我正在使用 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()

最佳答案

只需删除/:

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

注意:

Do not set cnopts.hostkeys = None, unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.

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

如果 auto_add_key=True

auto_add_key 会将 key 添加到 known_hosts
一旦 known_hosts 中存在主机 key ,就会检查该 key 。

请引用Martin Prikryl -> answer关于安全问题。

Why using context manager is a good approach :

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()

关于python - SFTP 无法识别上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57715928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com