Wil*_*tin 7 scripting bash sftp
我正在编写一个 BASH shell 脚本来将目录中的所有文件上传到远程服务器,然后将它们删除。它将通过 CRON 作业每隔几个小时运行一次。
我的完整脚本如下。基本问题是应该确定文件是否上传成功的部分不起作用。无论上传是否成功,SFTP 命令的退出状态始终为“0”。
如何确定文件是否正确上传,以便我知道是删除它还是放任不管?
#!/bin/bash
# First, save the folder path containing the files.
FILES=/home/bob/theses/*
# Initialize a blank variable to hold messages.
MESSAGES=""
ERRORS=""
# These are for notifications of file totals.
COUNT=0
ERRORCOUNT=0
# Loop through the files.
for f in $FILES
do
# Get the base filename
BASE=`basename $f`
# Build the SFTP command. Note space in folder name.
CMD='cd "Destination Folder"\n'
CMD="${CMD}put ${f}\nquit\n"
# Execute it.
echo -e $CMD | sftp -oIdentityFile /home/bob/.ssh/id_rsa bob@ftp.example.edu
# On success, make a note, then delete the local copy of the file.
if [ $? == "0" ]; then
MESSAGES="${MESSAGES}\tNew file: ${BASE}\n"
(( COUNT=$COUNT+1 ))
# Next line commented out for ease of testing
#rm $f
fi
# On failure, add an error message.
if [ $? != "0" ]; then
ERRORS="${ERRORS}\tFailed to upload file ${BASE}\n"
(( ERRORCOUNT=$ERRORCOUNT+1 ))
fi
done
SUBJECT="New Theses"
BODY="There were ${COUNT} files and ${ERRORCOUNT} errors in the latest batch.\n\n"
if [ "$MESSAGES" != "" ]; then
BODY="${BODY}New files:\n\n${MESSAGES}\n\n"
fi
if [ "$ERRORS" != "" ]; then
BODY="${BODY}Problem files:\n\n${ERRORS}"
fi
# Send a notification.
echo -e $BODY | mail -s $SUBJECT bob@example.edu
Run Code Online (Sandbox Code Playgroud)
由于一些让我头疼的操作考虑,我不能使用SCP。远程服务器在 Windows 上使用 WinSSHD,并且没有 EXEC 权限,因此任何 SCP 命令都会失败并显示消息“Exec request failed on channel 0”。因此上传必须通过交互式 SFTP 命令完成。
如果您批量处理 SFTP 会话,退出状态$?
会告诉您传输是否失败。
echo "put testfile1.txt" > batchfile.txt
sftp -b batchfile.txt user@host
if [[ $? != 0 ]]; then
echo "Transfer failed!"
exit 1
else
echo "Transfer complete."
fi
Run Code Online (Sandbox Code Playgroud)
编辑添加:这是我们在工作中的生产脚本中使用的东西,所以我确定它是有效的。我们不能使用 scp,因为我们的一些客户使用的是 SCO Unix。
归档时间: |
|
查看次数: |
44374 次 |
最近记录: |