简体   繁体   English

使用 pysftp 下载文件

[英]Downloading file with pysftp

I'm trying to load (and directly save locally) a .csv file stored on a FTP Server (SFTP protocol).我正在尝试加载(并直接在本地保存)存储在 FTP 服务器(SFTP 协议)上的.csv文件。 I'm using Python in combination with pysftp library.我将 Python 与 pysftp 库结合使用。 When I check if the file exists, it returns TRUE.当我检查文件是否存在时,它返回 TRUE。 But when trying to load the file, it seems to be empty, whatever I try.但是在尝试加载文件时,无论我尝试什么,它似乎都是空的。

How can I get (and store) the file to my local environment?如何将文件获取(和存储)到我的本地环境? Do I miss something obvious?我错过了一些明显的东西吗?

import pysftp

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

# Make connection to sFTP
with pysftp.Connection(hostname,
                       username=sftp_username,
                       password=sftp_pw,
                       cnopts = cnopts
                       ) as sftp:
    sftp.isfile('directory/file.csv')) ## TRUE
    file = sftp.get('directory/file.csv')
    print(file) ## None

sftp.close()

Connection.get does not return anything. Connection.get不返回任何内容。 It downloads the remote file to a local path specified by the localpath argument.它将远程文件下载到localpath参数指定的本地路径。 If you do not specify the argument, it downloads the file to the current working directory.如果不指定参数,它会将文件下载到当前工作目录。

So if you want to download to a specific local directory instead, you want this:因此,如果您想下载到特定的本地目录,则需要:

sftp.get('directory/file.csv', '/local/path/file.csv')

If you really want to read the file to a variable (what I understand that you actually do not want), you need to use Connection.getfo , like:如果您真的想将文件读入变量(我理解您实际上不想要),则需要使用Connection.getfo ,例如:

flo = BytesIO()
sftp.getfo(remotepath, flo)
flo.seek(0)

Alternatively, use Paramiko library directly (without the pysftp wrapper).或者,直接使用 Paramiko 库(没有 pysftp 包装器)。
See Read a file from server with SSH using Python .参阅使用 Python 使用 SSH 从服务器读取文件


Obligatory warning: Do not set cnopts.hostkeys = None , unless you do not care about security.强制性警告:不要设置cnopts.hostkeys = None ,除非您不关心安全性。 For the correct solution see Verify host key with pysftp .有关正确的解决方案,请参阅使用 pysftp 验证主机密钥

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM