我正在尝试加载存储在FTP服务器上的.csv文件(SFTP协议)。我将Python与pysftp库结合使用。在FTP服务器上,CSV文件位于.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()发布于 2020-02-28 03:46:32
如果您对远程主机具有ssh访问权限,并且对所需压缩文件的远程路径和该主机上的压缩实用程序有足够的了解,则可以使用ssh客户机远程运行解压缩命令并捕获其输出。在这里,我的目标是一台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)https://stackoverflow.com/questions/60428705
复制相似问题