使用scp-command将特定文件从服务器复制到本地计算机(Linux)

时间:2013-09-24 07:47:17

标签: linux bash shell

我使用基于Linux的操作系统。 比方说,我有一个服务器包含10个文件,如tmp1 .... tmp10,我想将三个特定文件复制到我的本地机器,比方说,tmp3,tmp7和tmp10。在这种情况下,我必须使用“scp-command”三次,我必须输入三次密码。问题是,我必须经常这样做,所以我“写下”下面的脚本。 我的问题是,脚本运行时没有任何错误消息,但文件不会被复制。

echo "insert path of source:" #prompt to enter the path of files you want to copy
read SOURCE                   # saving the path in the variable SOURCE
echo "insert path of target:" #prompt to enter the path, where you want to past the copied files 
read TARGET                   # saving the path in the variable SOURCE
echo "Insert the port"        # prompt to enter the port of the server
read port                     # saving the port in the variable PORT
echo "Password?"              # asking for password
read -s -a PASSWORD           # saving the password in the variable PASSWORD
x=(tmp1 tmp2)                 # An array contains the files i want to copy.
for i in "${x[@]}"            # A for-loop to copy each of the files in the array (x) from the SOURCE to the TARGET
do
  echo "the file $i"          # just to check if the array has been read.
#!/usr/bin/expect -f          # to read the expect-programm
  expect -c " 
            spawn /usr/bin/scp -P $prot $SOURCE/$i $TARGET
            expect { 
           "Password:" { send $PASSWORD\r\n; interact } 
           eof { exit } 
           }
            exit
            "
done                         # End of the for-loop
PASSWORD=0                   # To delete the variable PASSWORD

提前谢谢!!

3 个答案:

答案 0 :(得分:0)

您可以使用scp复制多个文件。例如:

scp remote:tmp{3,7,10} local

答案 1 :(得分:0)

scp正在使用ssh进行远程身份验证。 有多种方法可以解决您的问题: - 使用ssh代理并设置基于密钥的登录 - 这更安全。 在以下链接中有关于设置ssh以使用基于密钥的登录的方法 https://help.ubuntu.com/community/SSH/OpenSSH/Keys - 使用pscp工具,允许您使用-pw参数直接将密码传递给它。

答案 2 :(得分:0)

首先,我建议您使用public key authentication,这样您就不必担心脚本中的密码了。使用ssh-copy-id脚本(至少在Ubuntu中)将密钥复制到您将使​​用的主机上。

我会像@Joni已经提到的那样,通过一次调用复制多个文件。然后,如果你必须继续使用密码,我会让scp命令处理密码提示。