【问题标题】:Python copy file to remotePython复制文件到远程
【发布时间】:2021-10-29 16:10:36
【问题描述】:

我正在使用此代码

tar zcf - somefolder/ | ssh user@server "cd /path/to/remote && tar zxf -"

在两个系统之间复制文件

我想用python来做

我做了

import subprocess
p=subprocess.Popen('tar zcf - somefolder/ | ssh user@server "cd /path/to/remote && tar zxf -')

我也试过了

p=subprocess.Popen(["tar","-zcf somefolder | ssh ubuntu@192.168.100.110 /path/to/remote && tar -zxf"])

但两者都不起作用 我也试过用 run 而不是 popen 但还是不行

但是

 stream = os.popen("cmd")

这工作正常,但问题是我没有获得状态

我可以使用的第一种方法

 os.waitpid(p.pid, 0)

获取进程的实时状态

我想要的是在不使用外部库的情况下在远程和本地之间传输文件 并具有实时状态

我怎样才能做到这一点?

【问题讨论】:

    标签: python linux file-transfer


    【解决方案1】:

    我会保持简单并使用 os 模块,它也比 subprocess 更快:

    result = os.popen("command").read()

    【讨论】:

    • 我怎样才能在这个方法中获得状态?
    • @Harishuw 使用此命令将强制程序等待命令完成。无需检查状态。当结果准备好时,命令就完成了。
    【解决方案2】:

    更新:抱歉,我忽略了“没有外部模块”。但也许它对其他搜索有用。

    有一个模块:)

    from paramiko import SSHClient
    from scp import SCPClient
    
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.connect('example.com')
    
    # SCPCLient takes a paramiko transport as an argument
    scp = SCPClient(ssh.get_transport())
    
    scp.put('test.txt', 'test2.txt')
    scp.get('test2.txt')
    
    # Uploading the 'test' directory with its content in the
    # '/home/user/dump' remote directory
    scp.put('test', recursive=True, remote_path='/home/user/dump')
    
    scp.close()
    

    或者使用with:

    from paramiko import SSHClient
    from scp import SCPClient
    
    with SSHClient() as ssh:
        ssh.load_system_host_keys()
        ssh.connect('example.com')
    
        with SCPClient(ssh.get_transport()) as scp:
            scp.put('test.txt', 'test2.txt')
            scp.get('test2.txt')
    

    见:https://pypi.org/project/scp/

    【讨论】:

      【解决方案3】:

      根据我的经验,使用subprocess.run() 运行外部 Ubuntu 程序/进程我不得不使用每个命令参数或不同的列表条目,如下所示:

      subprocess.run(['pip3', 'install', 'someModule'])

      所以也许可以尝试将每个以空格分隔的参数作为它自己的列表元素。

      【讨论】:

        猜你喜欢
        • 2021-03-25
        • 1970-01-01
        • 2022-01-07
        • 2013-02-26
        • 1970-01-01
        • 2015-06-24
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        相关资源
        最近更新 更多