2017-06-05 71 views
0

考虑你有一个文本文件中的千位IP地址列表 - 每行一个。我希望能够使用openssl s_client命令从每个IP地址获取所有可能的异常。到目前为止,异常是证书过期,自签名证书和颁发者要包括[email protected]。总之,我希望能够获得每个IP地址的简明错误消息(如果有的话)。我现在的bash脚本的样子:如何从openssl命令写入grep的输出?

for ip in `awk '{print $1}' < general_certs.txt`; do 
# Print IP address currently checking 
echo -e $ip; 
    if timeout 30 openssl s_client -connect $ip:443| grep -i 'error' ; then 
# Write error information and IP address to a file 
     echo `openssl s_client -connect $ip:443| grep -i 'error'` $ip >> general_errors; 
    else 
# Write noerror information and IP address to another file 
     echo "noerror" $ip >> general_noerror; 
    fi; 
done 

第一个问题我的代码是,它是不是最优化的,我是持怀疑态度的,如果它返回准确的结果。上述脚本的最终目标是识别包含IP的所有不可信证书。

第二个问题我用上面的代码,我不能先echo $ ip,因为它会被消息本身截断。所以,我最终在错误信息后写出了$ ip。

如果我的问题有更真实的解决方案,则不需要使用openssl。

回答

0

您可以尝试通过将流程在后台运行它们都在同一个镜头:

#!/bin/bash 
max=100 
counter=0 
for ip in `awk '{print $1}' < general_certs.txt`; do 
    ((counter++)) 
    (
     results=$(timeout 30 openssl s_client -connect $ip:443 2> /dev/null) 
     if [ "$results" = "" ]; then 
      echo "$ip noresponse" 
     else 
      echo -n "$ip " 
      echo "$results" | grep -i 'error' || echo "noerror" 
     fi 
    ) >> general_errors & 
    if [ $counter -eq $max ]; then 
     wait 
     counter=0 
    fi 
done 
wait 

这是输入:

$ cat general_certs.txt 
stackoverflow.com 
redhat.com 
google.com 
8.8.8.8 
vt.edu 
bls.gov 
8.8.4.4 

这是输出:

$ cat general_errors 
8.8.4.4 noerror 
stackoverflow.com noerror 
google.com noerror 
vt.edu noerror 
bls.gov noerror 
redhat.com noerror 
8.8.8.8 noresponse 

如果你有一些失败,我可以测试它们。

+0

我想选择你的答案是正确的,但如果我有过大的IP列表,你的方法可能会冻结操作系统。 – K4rt

+0

只需在循环中添加一个计数器即可。当计数器达到最大值时,调用'wait'并重置计数器。 – Jack

+0

更改了代码以添加计数器逻辑。 – Jack

0

如果您正在尝试获取哪些IP具有不可信证书,则可以使用curl尝试,即使它不是最佳选项。

喜欢的东西:

for ip in `awk '{print $1}' < general_certs.txt`; do 
    echo -e $ip                                      

    curl https://${ip}:443 &> /dev/null                                

    if [ $? == 51 ]; then                
    echo "upsis, https://${ip}:443 has a untrusted certificate" >> general_err 
    else                    
    echo "yai, https://${ip}:443 doesn't have a untrusted certificate" >> general_noerr 
    fi 
done 

请注意,在这里你只检查unstrusted证书(误差51卷曲),但该命令可以发送任何其他错误,它会去general_noerror