【问题标题】:Read tar file on remote SSH server without using FTP in Python在 Python 中不使用 FTP 读取远程 SSH 服务器上的 tar 文件
【发布时间】:2017-03-21 09:40:48
【问题描述】:

我正在远程服务器上创建一些 tar 文件,我希望能够将它传送到我的机器上。由于安全原因,我无法在该服务器上使用 FTP。

所以我怎么看,我有两个选择:

  1. 以其他方式获取文件(作为文件),然后使用 tarfile 库 - 如果是这样,我需要在不使用 FTP 的情况下获取文件的帮助。

  2. 获取文件内容,然后解压。

如果有其他方法,我想听听。

import spur

#creating the connection
shell = spur.SshShell(
    hostname=unix_host,
    username=unix_user,
    password=unix_password,
    missing_host_key=spur.ssh.MissingHostKey.accept
    )

# running ssh command that is creating a tar file on the remote server
with shell:
    command = "tar -czvf test.gz test"
    shell.run(
        ["sh", "-c", command],
        cwd=unix_path
        )

    # getting the content of the tar file to gz_file_content
    command = "cat test.gz"
    gz_file_content = shell.run(
        ["sh", "-c", command],
        cwd=unix_path
        )

更多信息: 我的项目在 virtualenv 上运行。我正在使用 Python 3.4。

【问题讨论】:

  • 如果你有 ssh,那么也许你有 scp 或 sftp。
  • 不要使用missing_host_key=spur.ssh.MissingHostKey.accept!你正在失去对Man-in-the-middle attacks的保护!

标签: python ssh ftp tar


【解决方案1】:

如果您有 SSH 访问权限,那么您有 99% 的 SFTP 访问权限。

因此您可以使用 SFTP 下载文件。见Download files over SSH using Python


或者一旦你使用了spur,查看它的SshShell.open method

例如,要通过 SSH 复制二进制文件,假设您已经有一个 SshShell 的实例:

with ssh_shell.open("/path/to/remote", "rb") as remote_file:
    with open("/path/to/local", "wb") as local_file:
        shutil.copyfileobj(remote_file, local_file)

SshShell.open 方法在后台使用 SFTP(通过 Paramiko 库)。

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2020-09-16
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多