gpt4 book ai didi

python - 使用 Paramiko 通过 Python 和 Pythonista 上传 SFTP。无法创建目录/子目录

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:48 25 4
gpt4 key购买 nike

我正在尝试将图像上传到远程服务器上的上传文件夹。文件夹结构始终为 uploads/year/month/而且我无法让 paramiko 检查文件夹是否存在,如果不存在则创建它们。

SSH 连接正常,上传文件也正常,但无法在上传目录中创建子文件夹。

我遇到了看起来像解决方案 here 的东西.我也有同样的问题,但是我在 iOS 上使用 Pythonista。选项 A:我的代码完全错误或选项 B,这是一个 iOS/Pythonista 特定问题。

因此,来自另一个线程(上面链接)的代码设置了一个定义并运行一个 try/error 循环来测试通过它的文件夹是否已经存在,如果不存在则创建它们。在我下面的脚本中,它是 # Set Definition for "mkdir -p" .

remoteFilePath 调用它……

  1. 不必要,因为:理想情况下,它应该只测试 datePath存在,因为 remotePath绝对存在
  2. 可能有问题,因为: fileName没有路径,将由下一个命令放在那里。

我尝试调整脚本,但不知何故我无法让它工作。

无论我尝试什么我都会出错:

  • 版本 1:TypeError: mkdir_p() takes exactly 2 arguments (1 given)"
  • 版本 2:AttributeError: 'tulpe' object has no attribute 'rfind'
  • 版本 3:Exception: unknown type for (/home/userZ/Dropbox/uploads/year/month', 'test.png') type <type 'tuple'>

这是脚本相关部分的片段(或者 gist,如果您喜欢它的外观):

# Set Variables
fileName = "temp.png"
remotePath = "/home/userZ/Dropbox/uploads/"
datePath = "year/month/"
remoteFilePath = remotePath + datePath + fileName #

# Set Definition for "mkdir -p"
def mkdir_p(sftp,remote_directory):
remote_dirname, basename = os.path.split(remote_directory)
mkdir_p(os.path.dirname(remote_directory))
try:
sftp.chdir(name)
except IOError:
sftp.mkdir(name)
sftp.chdir(name)

try:
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport) # Start SFTP client

# Try to make remote path - 3 Versions and all fail
mkdir_p(sftp,remoteFilePath) # Version 1
#mkdir_p(sftp, os.path.split(remoteFilePath)) # Version 2
#sftp.mkdir(os.path.split(remoteFilePath)) # Version 3

# Put file to remote
sftp.put('temp.png', remoteFilePath)

# Close connection
finally:
transport.close()
sftp.close()

感谢任何帮助。 (注意:OP = Python noob)。我依赖 Paramiko,因为我的共享主机只支持 SFTP。否则我会选择 FTPlib。

最佳答案

你用FTP遇到了同样的问题,你不能mkdir/some/long/path,你必须

cd /
mkdir some # ignore errors if it exists
cd some
mkdir long # ignore errors if it exists
cd long
mkdir path # ignore errors if it exists
cd path

我猜这个模型的历史原因是为客户端发出的任何命令提供一个简单的 bool 值 SUCCEED/FAIL。

出现一些模糊错误,例如“无法创建目录 /some/long/path,因为目录 /some/long 不存在”将是一种痛苦在客户端处理的屁股。

在查看 SFTP 协议(protocol)规范 re: filenames ( https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-13#page-15 ) 时,我不清楚客户是否应该在创建目录的上下文中将“/”理解为路径分隔符——因为你可以有一个 SFTP windows box 上的服务器也是如此,paramiko 可能会完全忽略对此的支持?

tl;dr:修改你的代码,将路径拆分成它的各个部分,尝试 chdir 到它们,如果失败,尝试创建它们,如果失败你就死定了,否则 chdir 到下一个子目录和继续,直到您没有更多的子目录可以创建。

编辑

你在线路上遇到的具体问题

mkdir_p(os.path.split(remoteFilePath))

可以通过将其更改为来修复

mkdir_p(sftp, os.path.split(remoteFilePath))

关于python - 使用 Paramiko 通过 Python 和 Pythonista 上传 SFTP。无法创建目录/子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18047808/

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