SFTP bash shell 脚本将文件从源复制到目标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53761918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 17:03:36  来源:igfitidea点击:

SFTP bash shell script to copy the file from source to destination

bashshellsftpcopying

提问by Ashish Sood

I have created one script to copy the local files to the remote folder, the script is working fine outside of if condition but when I enclosed inside the if condition the put command is not working and logged into the remote server using sftp protocol and when exist it's showing the error: put command not found

我创建了一个脚本来将本地文件复制到远程文件夹,该脚本在 if 条件之外工作正常,但是当我将 if 条件括起来时,put 命令不起作用并使用 sftp 协议登录到远程服务器,当存在时它显示错误:未找到放置命令

see what is happening after executing the script

查看执行脚本后发生了什么

Connected to 10.42.255.209.
sftp> bye
sftp.sh: line 23: put: command not found

Please find the below script.

请找到以下脚本。

echo -e;
echo -e "This script is used to copy the files";
sleep 2;

localpath=/home/localpath/sftp
remotepath=/home/destination/sftp/

        if [ -d $localpath ]
         then
           echo -e "Source Path found"
           echo -e "Reading source path"
           echo -e "Uploading the files"
           sleep 2;

                sftp [email protected]
                put $localpath/* $remotepath

        else

回答by nos

In a simple case such as this, you could use scpinstad of sftpand specify the files to copy on the command line:

在像这样的简单情况下,您可以使用scpinstad ofsftp并在命令行上指定要复制的文件:

 scp $localpath/* [email protected]:/$remotepath/

But if you would rather want to issue sftp commands, then sftp can read commands from its stdin, so you can do:

但是,如果您更愿意发出 sftp 命令,那么 sftp 可以从其标准输入读取命令,因此您可以执行以下操作:

  echo "put $localpath/* $remotepath" | sftp [email protected]

Or you can use a here documentto pass data as stdin to sftp, which might be easier if you want to run several sftp commands:

或者,您可以使用here 文档将数据作为 stdin 传递到 sftp,如果您想运行多个 sftp 命令,这可能会更容易:

sftp [email protected] << EOF
put $localpath/fileA $remotepath/
put $localpath/fileB $remotepath/
EOF

Finally, you could place the sftp commands in a separate file, say sftp_commands.txt, and have sftp execute those commands using its -bflag:

最后,您可以将 sftp 命令放在一个单独的文件中,例如sftp_commands.txt,并让 sftp 使用其-b标志执行这些命令:

 sftp -b ./sftp_commands.txt [email protected]