2017-06-05 62 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