python - 使用 python 通过 SSH 通过管道传输的 Tar 文件传输
问题描述
我想在 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 代码来做到这一点?谢谢
解决方案
你可以用 paramiko 的SFTP
客户端来做。有几种方法可以打开 sftp 传输(请参阅docs和demo),但为了简单起见,这里有一个示例,我计算传输的文件并使用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
推荐阅读
- mysql - 在 MySQL 中合并两个查询以获得一个结果
- swift - NavigationLink 正在将数组中的错误记录传递给另一个视图
- javascript - 正则表达式或子字符串操作从关键字中删除 URL
- python - 具有顺序的pytorch concat层
- c# - C#无法为具有类A属性的类B调用构造函数。错误:不可调用的成员不能像方法一样使用
- angular - Angular 10 HttpClient 未设置正确的 Content-Type 标头
- c++ - libcurl解析响应标头并存储为键值对c ++
- python - PyQT5 空白窗口
- reactjs - 用酶和玩笑测试 Formik 形式
- python-3.x - 如何在列表框中创建列?