如何使shell脚本循环不会因错误而停止

时间:2011-06-16 08:25:40

标签: scripting

我有一个主shell脚本,它为循环的每次迭代调用子脚本,如下所示:

#!/bin/bash

while read line
do
    if [[ $line != "" ]]
    then
        ./sslv2_check.sh $line
    fi
done < https-servers

如果这些调用中有任何一个调用(参见下面的shell脚本)

message="FAIL! $1 supports SSLv2 on port $port"

然后主脚本将停止,不会调用下一批。我该如何继续?

#!/bin/bash

# Required Argument $1 = hostname
# Optional Argument $1 = port number
if [[ $1 == "" ]]
then
    echo Error: I expected a hostname to be passed as an argument but didn\'t find any
    exit 1
fi

if [[ $2 == "" ]]
then
    port=443
else
    port=$2
fi

date=$(date +"%Y-%m-%d")
datetime=$(date +"%Y-%m-%d-%H-%M")
errorlogfile=logs/$date.error.log
logfile=logs/$date.log
# Testing for SSLv2
output=$(openssl s_client -connect $1:$port -ssl2 2>&1)
if [[ $output == *"handshake failure"* ]]
then
    message="PASS! SSLv2 not supported by $1 on port $port"
elif [[ $output == *"104"* ]]
then
    message="PASS! SSLv2 is not supported by $1 on port $port"
elif [[ $output == *"null ssl method passed"* ]]
then
    message="ERROR! SSLv2 is not enabled on your local machine"
    # Log error
    echo "$datetime -- $message" >> $errorlogfile
    echo $output >> $errorlogfile
elif [[ $output == *"110"* ]]
then
    message="ERROR! Failed to connect to $1. Make sure you type in the hostname correctly etc."
    # Log error
    echo "$datetime -- $message" >> $errorlogfile
    echo $output >> $errorlogfile
elif [[ $output == *"BEGIN CERTIFICATE"* ]]
then
    message="FAIL! $1 supports SSLv2 on port $port"
    # Log error
    echo "$datetime -- $message" >> $errorlogfile
    echo $output >> $errorlogfile
else
    message="ERROR! An unknown error occurred. See $errorlogfile for details"
    echo "$datetime -- $message" >> $errorlogfile
    echo $output >> $errorlogfile
fi
#stdout the message
echo $message
#Log the message
echo "$datetime -- $message" >> $logfile

2 个答案:

答案 0 :(得分:0)

您可以尝试这一点,如果您的其他脚本失败,echo将始终成功。

if [[ $line != "" ]]
then
    ./sslv2_check.sh $line || echo "failed"
fi

答案 1 :(得分:0)

一旦openssl连接,它会在关闭之前等待输入。我不知道为什么,但这导致主批脚本中止。解决方案如下:

替换

output=$(openssl s_client -connect $1:$port -ssl2 2>&1)

output=$(echo 'GET HTTP/1.0' | openssl s_client -connect $1:$port -ssl2 2>&1)