bash – 在脚本化命令行SFTP会话中检测上载成功/失败?
发布时间:2020-12-15 18:33:03 所属栏目:安全 来源:网络整理
导读:我正在编写一个BASH shell脚本,将目录中的所有文件上传到远程服务器,然后删除它们.它将通过CRON作业每隔几个小时运行一次. 我的完整脚本如下.基本问题是,应该判断文件是否成功上传的部分不起作用.无论上载是否成功,SFTP命令的退出状态始终为“0”. 如何判断
我正在编写一个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}nquitn" # 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.nn" if [ "$MESSAGES" != "" ]; then BODY="${BODY}New files:nn${MESSAGES}nn" fi if [ "$ERRORS" != "" ]; then BODY="${BODY}Problem files:nn${ERRORS}" fi # Send a notification. echo -e $BODY | mail -s $SUBJECT bob@example.edu 由于一些让我头疼的操作方面的考虑因素,我无法使用SCP.远程服务器在Windows上使用WinSSHD,并且没有EXEC权限,因此任何SCP命令都会失败并显示消息“通道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 编辑添加:这是我们在工作中的生产脚本中使用的东西,所以我确信它是有效的.我们不能使用scp,因为我们的一些客户在SCO Unix上. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |