简体   繁体   English

Python复制文件到远程

[英]Python copy file to remote

I am using this code我正在使用此代码

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

to copy files between 2 system在 2 个系统之间复制文件

i want to do it in python我想用python来做

i did我做了

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

i also tried我也试过

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

but both not working i also tried with run instead of popen but still not working但两者都不起作用我也试过用 run 而不是 popen 但仍然不起作用

but

 stream = os.popen("cmd")

this is working fine but problem is i am not getting status这工作正常,但问题是我没有获得状态

in first methods i can use在我可以使用的第一种方法中

 os.waitpid(p.pid, 0)

to get live status of process获取进程的实时状态

what i want is transfer files between remote and local without using external libraries and with live status我想要的是在不使用外部库和实时状态的情况下在远程和本地之间传输文件

how can i achive this?我怎样才能做到这一点?

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

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

Update: I overlooked "no external module" sorry.更新:抱歉,我忽略了“无外部模块”。 But maybe it's useful for others searching.但也许它对其他人搜索有用。

There is a module for that :)有一个模块:)

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()

Or with usage of with :或者使用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')

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

From my experience, using subprocess.run() to run an external Ubuntu program/process I've had to use each command parameter or such as a different list entry, like so:根据我的经验,使用subprocess.run()运行外部 Ubuntu 程序/进程我不得不使用每个命令参数或例如不同的列表条目,如下所示:

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

So maybe try putting every single space-separated argument as it's own list element.所以也许可以尝试将每个空格分隔的参数都作为它自己的列表元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM