我想复制文件从/到远程服务器在不同的目录。 例如,我想一次运行这4个命令。

scp remote:A/1.txt local:A/1.txt
scp remote:A/2.txt local:A/2.txt
scp remote:B/1.txt local:B/1.txt
scp remote:C/1.txt local:C/1.txt

最简单的方法是什么?


当前回答

正如Jiri提到的,可以使用scp -r user@host:/some/remote/path /some/local/path递归地复制文件。这假设有一个目录包含所有您想要传输的文件(没有其他文件)。

但是,如果你想从多个不同的目录传输文件,并且目的地不相同,SFTP提供了一种替代方案:

sftp user@host << EOF
  get /some/remote/path1/file1 /some/local/path1/file1
  get /some/remote/path2/file2 /some/local/path2/file2
  get /some/remote/path3/file3 /some/local/path3/file3
EOF

这里使用“here doc”语法定义一系列SFTP输入命令。作为一种替代方法,您可以将SFTP命令放在一个文本文件中,并执行SFTP user@host -b batchFile.txt

其他回答

{file1,file2,file3}的答案仅适用于bash(在远程或本地)

真正的方法是:

scp user@remote:'/path1/file1 /path2/file2 /path3/file3' /localPath

在我的案例中,有太多名称不相关的文件。

我最后用了,

$  for i in $(ssh remote 'ls ~/dir'); do scp remote:~/dir/$i ./$i; done
1.txt                                         100%  322KB   1.2MB/s   00:00
2.txt                                         100%   33KB 460.7KB/s   00:00
3.txt                                         100%   61KB 572.1KB/s   00:00

$

问题:使用单个SCP命令将多个目录从远程服务器复制到本地计算机,并保留每个目录在远程服务器中的原样。

解决方案:SCP可以很容易地做到这一点。这解决了在对多个文件夹使用SCP时需要多次输入密码的烦人问题。因此,这也节省了很多时间!

e.g.

# copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command

~$ cd ~/working/directory
~$ scp -r username@contact.server.de:/work/datasets/images/test/\{t1,t2,t3\}  .

PS:受到这个伟大答案的激励:scp或sftp用一个命令复制多个文件


根据注释,这在Windows上的Git Bash中也可以正常工作

在玩了一段时间scp之后,我找到了最健壮的解决方案:

(注意单引号和双引号)

本地到远端:

scp -r "FILE1" "FILE2" HOST:'"DIR"'

远程到本地:

scp -r HOST:'"FILE1" "FILE2"' "DIR"

注意,“HOST:”后面的内容将被发送到远程服务器并在那里进行解析。所以我们必须确保它们没有被本地shell处理。这就是使用单引号的原因。双引号用于处理文件名中的空格。

如果所有文件都在同一个目录中,我们可以使用*来匹配它们,例如

scp -r "DIR_IN"/*.txt HOST:'"DIR"'
scp -r HOST:'"DIR_IN"/*.txt' "DIR"

与使用只有某些shell支持的“{}”语法相比,这个语法是通用的

在我的例子中,我被限制只能使用sftp命令。 所以,我必须使用带有sftp的批处理文件。我创建了如下所示的脚本。这假设您在/tmp目录下工作,并且希望将文件放在远程系统的destdir_on_remote_system中。这也只适用于非交互式登录。您需要设置公钥/私钥,以便无需输入密码即可登录。根据需要进行更改。

#!/bin/bash

cd /tmp
# start script with list of files to transfer
ls -1 fileset1* > batchfile1
ls -1 fileset2* >> batchfile1

sed -i -e 's/^/put /' batchfile1
echo "cd destdir_on_remote_system" > batchfile
cat batchfile1 >> batchfile
rm batchfile1

sftp -b batchfile user@host