python - 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()
解决方案
只需删除/
:
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()
推荐阅读
- c# - 如何从字符串中获取整数数组
- elasticsearch - Elastic 7.X 根映射定义具有不受支持的参数
- sql - 如何循环遍历一个表并根据另一个表中的数据更新特定列?
- tfs - TFS 构建任务可以从 repo 中签出特定的提交,而不是签出完整的 repo
- elasticsearch - 循环浏览无痛但“未找到字段”的项目
- python - 处理打开不存在文件“unknown_file.txt”并打印消息文件未找到的脚本。给用户
- spss-modeler - 如何在 SPSS Modeler 中选择“Multinominal”和“Bionominal”?
- r - 将列表中的多个数据框转换为它们自己唯一的语料库对象
- sql - ORA-21780: 超出对象持续时间的最大数量
- xml - 检索 XML 节点结构 - Bash