使用 paramiko 将文件从远程目录复制到远程子目录

Copy file from remote dir to remote sub directory using paramiko

如何将远程服务器 /maindir/fil1.txt 中的文件复制到子目录 /maindir/subdir/file1.txt 我使用 paramiko 创建了 sftp。但它总是检查要从 .

复制的本地路径
filename_full_path='/maindir/fil1.txt'
destfilename_full_path='/maindir/subdir/file1.txt'
sftp.put(filename_full_path, destfilename_full_path)

如何告诉sftp本地路径也在远程主机中?

您可以通过以下方式尝试

   a=paramiko.SSHClient()
   a.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   a.connect('ip',username='user',password='passw')
   stdin, stdout, stderr = a.exec_command("cp /sourc/file /target/file")

核心SFTP协议不支持复制远程文件。 有 copy-data/copy-file extension to the SFTP protocol.

的草稿

但在最广泛使用的 OpenSSH SFTP 服务器中,copy-data 受到最新的 version 9.0 only. Another servers that do support the extensions are ProFTPD mod_sftp 和 Bitvise SFTP 服务器的支持。

所以即使Paramiko支持(不支持),也可能对你没有任何用处。


备选方案:

  • 下载文件夹并将其重新上传到新位置(纯 SFTP 解决方案)
  • 在“执行”通道中使用 cp 命令(不再是 SFTP,需要 shell 访问权限)– 使用 SSHClient.exec_command.
  • 很多错误复制移动。支持将文件移动到另一个文件夹。

您不能像我们通常在操作系统中那样复制或移动文件。 您需要按照此进行文件传输。

import paramiko
ssh_client =paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=’hostname’,username=’something’,password=’something_unique’)

ftp_client=ssh_client.open_sftp()
ftp_client.put(‘localfilepath’,remotefilepath’)   #for Uploading file from local to remote machine
#ftp_client.get(‘remotefileth’,’localfilepath’)   for Downloading a file from remote machine

ftp_client.close()