【问题标题】:Downloading CSV inside a .zip with pysftp使用 pysftp 在 .zip 中下载 CSV
【发布时间】:2020-06-11 04:46:43
【问题描述】:

我正在尝试加载存储在 FTP 服务器(SFTP 协议)上的 .csv 文件。我将 Python 与 pysftp 库结合使用。在 FTP 服务器上,CSV 文件位于 .zip 文件中。有没有办法打开 zip,然后只检索其中的 csv 文件?

提前谢谢你,

import pysftp

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

# Make connection to sFTP
with pysftp.Connection(hostname,
                       username=sftp_username,
                       password=sftp_pw,
                       cnopts = cnopts
                       ) 
with pysftp.cd(download_directory):
        with sftp.cd('download_directory'):
            print(f'Downloading this file: {filename}')
            sftp.get(filename, preserve_mtime=True)
    sftp.close()

【问题讨论】:

  • 只是为了清楚起见...该 .zip 中还有其他文件吗?
  • 注意:SFTP 和 FTP 是非常不同的协议。但这对您的问题无关紧要:开箱即用,我不知道 FTP 和 SFTP 服务器都不允许从服务器端的 ZIP 存档中提取元素。但是专门的服务可以...
  • 如果你有 sftp,你可能也有 ssh。运行该文件的远程解压缩,返回流是您想要的 csv 怎么样?
  • ZIP 文件中是否还有其他文件? => 如果您只想要一个很小的 ​​CSV 文件(与巨大的 ZIP 文件相比),那么问题的重点是避免下载整个 ZIP 文件吗?正如@Serge 声称的那样,这并非不可能(您确实必须在本地 提取文件,但您不必为此下载整个ZIP)。 SFTP 绝对可以只下载(ZIP)文件的一部分。还有一些 FTP 服务器。所以重要的是,它是 SFTP 还是 FTP。

标签: python flask ftp


【解决方案1】:

如果您对远程主机具有ssh 访问权限,并且对所需 zip 文件的远程路径和该主机上的 zip 实用程序有足够的了解,则可以使用 ssh 客户端远程运行 unzip 命令并捕获其输出。在这里,我的目标是一台 linux 机器,并且 zipfile 在登录用户的主目录路径中。我可以使用 paramiko ssh 客户端来完成这项工作

最好通过ssh登录远程服务器,练习看看路径结构是什么样的

import sys
import paramiko
import shutil

def sshclient_exec_command_binary(sshclient, command, bufsize=-1,
    timeout=None, get_pty=False):
    """Paramiko SSHClient helper that implements exec_command with binary
    output.
    """
    chan = sshclient._transport.open_session()
    if get_pty:
        chan.get_pty()
    chan.settimeout(timeout)
    chan.exec_command(command)
    stdin = chan.makefile('wb', bufsize)
    stdout = chan.makefile('rb', bufsize)
    stderr = chan.makefile_stderr('rb', bufsize)
    return stdin, stdout, stderr

# example gets user/pw from command line
if len(sys.argv) != 3:
    print("usage: test.py username password")
    exit(1)
username, password = sys.argv[1:3]

# put your host/file info here
hostname = "localhost"
remote_zipfile = "tmp/mytest.zip"
file_to_extract = "myfile"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=username, password=password)
unzip_cmd = "unzip -p {} {}".format(remote_zipfile, file_to_extract)
print("running", unzip_cmd)
stdin, out, err = sshclient_exec_command_binary(ssh, unzip_cmd)

# if the command worked, out is a file-like object to read.
print("writing", file_to_extract)
with open(file_to_extract, 'wb') as out_fp:
    shutil.copyfileobj(out, out_fp)

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 2020-05-16
    • 1970-01-01
    • 2018-01-21
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多