通过ssh将文件从一台服务器复制到另一台服务器的最简单方法是使用scp命令。为了调用scp,您需要subprocess模块。
import subprocess p = subprocess.Popen(["scp", "my_file.txt", "username@server:path"]) sts = os.waitpid(p.pid, 0)
您需要使用waitpid调用来等待复制完成。
另一个解决方案是打开ssh连接并使用scp模块。
from paramiko import SSHClient from scp import SCPClient ssh = SSHClient()ssh.load_system_host_keys() ssh.connect('user@server:path') with SCPClient(ssh.get_transport()) as scp: scp.put('my_file.txt', 'my_file.txt') # Copy my_file.txt to the server