【问题标题】:File transfer with Tar piped through SSH using python使用 python 通过 SSH 通过管道传输的 Tar 文件传输
【发布时间】:2018-05-21 21:55:02
【问题描述】:

我想在 python 中运行一个命令,例如:

  tar -cf - files | ssh -c arcfour128 user@remote "tar -xf - -C /directory/" 

我显然可以使用subprocess.run

subprocess.run("""tar -cf - %s | ssh -c arcfour128 user@remote "tar -xf - -C /directory/" """ % file_list ,shell=True))

但是,这样的命令既不提供进度信息,也不提供简单的异常管理。 例如,有没有办法使用库 tarfile 和 paramiko 使用本机 python 代码来做到这一点?谢谢

【问题讨论】:

  • 你能编辑这个以使用 Markdown 格式吗?
  • @MaxvonHippel - 编辑待定...添加您的投票!
  • @tdelaney 谢谢,它有效。但是,原始帖子中的命令略有不同:通过管道输出 tar 我避免了一个一个地发送文件。我有数以百万计的文件,因此 tar 是避免逐个发送文件的有效解决方案。我可以在遥控器上使用 tar 然后发送 tar 存档,但这有两个缺点:1. tar 文件需要时间来创建 2. tar 文件占用空间

标签: python file ssh server tar


【解决方案1】:

您可以使用 paramiko 的 SFTP 客户端来完成。有几种方法可以打开 sftp 传输(请参阅 docsdemo),但为了简单起见,这里有一个示例,我计算传输的文件并使用 put 函数的回调进行中间进度。

import paramiko
from glob import glob
import posixpath

def xfer_callback(cur, total):
    print("{}...{}".format(cur, total))

ssh_client =paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname="localhost",username="td",
    password="notmyrealpassword")
ftp = ssh_client.open_sftp()


remote_base = "/home/td/tmp/deleteme"

files = glob("*.py")
count = 1
for fn in files:
    print("sending {} of {}".format(count, len(files)))
    ftp.put(fn, posixpath.join(remote_base, fn), xfer_callback)
    count += 1

样本输出

$ python3 test.py
sending 1 of 6
411...411
sending 2 of 6
557...557
sending 3 of 6
453...453
sending 4 of 6
1117...1117
sending 5 of 6
32768...118000
65536...118000
98304...118000
118000...118000
sending 6 of 6
515...515

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 2016-02-26
    • 2011-01-31
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2016-06-14
    • 2019-01-24
    相关资源
    最近更新 更多