shell脚本中的SFTP错误处理

时间:2014-03-21 17:10:37

标签: shell error-handling scripting sftp

我正在编写一个从SFTP服务器下载文件的SH脚本。 我想知道在我的脚本的SFTP连接期间是否出现任何错误。 但没有重定向我的输出,也没有使用grep ,因为我已经将输出重定向到不同的日志文件。

我尝试制作类似于以下示例的命令,但我需要{---?---}部分。 我使用case语法作为示例,但我可以使用if或任何其他语法。

sftp <user>@<host>:<remote_file> <local_destination>

if [ $? != 0 ];
    then
        case {---?---} in
            {---?---})
                _error_exit "permission denied, please try again"
                ;;
            {---?---})
                _error_exit "SFTP server not responding, maybe offline"
                ;;
            {---?---})
                _error_exit "file not found"
                ;;
            *)
                _error_exit "unable to download the file from SFTP server"
        esac
    else
        _status "file downloaded"
    fi
}

1 个答案:

答案 0 :(得分:0)

OpenSSH sftp命令只有两个退出代码,0表示成功,1表示失败。

因此,如果您需要区分不同的错误,解析命令输出是您唯一的方法。

您可以将sftp命令输出重定向到临时文件,解析临时文件以查找错误消息,然后将临时文件打印到输出,以便它也包含在您的日志中。

sftp ... > /tmp/sftp.log
grep ... /tmp/sftp.log
...
cat /tmp/sftp.log