【问题标题】:unable to download files from sftp server using python无法使用 python 从 sftp 服务器下载文件
【发布时间】:2019-05-21 18:48:20
【问题描述】:

我正在编写一个 python 脚本来帮助我将文件从 sftp 服务器下载到我的本地文件夹。 当我运行脚本时,它只是下载空白文档 我继续尝试,但我失败了

我做了一个sftp服务器来测试代码,远程路径中指定的路径是服务器根目录

我在下面给出代码

import pysftp

myHostname = "192.168.56.1"
myUsername = "new45"
myPassword = "146515"

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword,cnopts=cnopts) as sftp:
    # Define the file that you want to download from the remote directory
    remoteFilePath = 'C:\\Users\\Simon\\Desktop\\ftp\\testfile.txt'

    # Define the local path where the file will be saved
    # or absolute "C:\Users\sdkca\Desktop\TUTORIAL.txt"
    localFilePath = 'C:\\Users\\Simon\\Desktop\\ftp2\\textfile.txt'

    sftp.get(remoteFilePath, localFilePath)

# connection closed automatically at the end of the with-block'''

请告诉我为什么正在下载空白文件的错误

【问题讨论】:

  • 该文件夹可能是 SFTP 服务器上的根目录。尝试从 remoteFilePath 中删除路径,然后将 testfile.txt 改为。如果这样不行,那么使用 CnOpts 上的 log 参数打开日志记录可能是值得的。

标签: python sftp paramiko


【解决方案1】:

使用任何 GUI SFTP 客户端登录到该服务器。并观察您的服务器使用的路径语法。绝对不是C:\Users\Simon\Desktop\ftp\testfile.txt。 SFTP 使用正斜杠。所以它可以像/C:/Users/Simon/Desktop/ftp/testfile.txt。但即使是完全不同的东西,特别是如果服务器或您的帐户是 chrooted

如果您直接在目标 Windows 系统上,您可能正在尝试使用您会使用的路径语法。但是您的 SFTP 服务器使用不同的路径语法呈现文件。您需要遵守该语法。

【讨论】: