首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用pysftp在.zip中下载CSV

使用pysftp在.zip中下载CSV
EN

Stack Overflow用户
提问于 2020-02-27 16:02:49
回答 1查看 1.1K关注 0票数 0

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

先谢谢你,

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2020-02-28 03:46:32

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

通过ssh登录到远程服务器并练习查看路径结构是一个好主意

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60428705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档