2016-11-24 4 views
0

netcatとの接続が成功した場合、どうすればスクリプトを停止できますか? たとえば、Connection to 192.168.2.4 21 port [tcp/ftp] succeeded!の場合、その文字列を保持する内容が不明です。nc接続がbashで成功した場合にスクリプトを停止する

#!/bin/bash 

#Find first 3 octets of the gateway and set it to a variable. 

GW=$(route -n | grep 'UG[ \t]' | awk '{print $2}' | cut -c1-10) 

#loop through 1 to 255 on the 4th octect 
for octet4 in {1..255} 
do 
     sleep .2 
     nc -w1 $GW$octet4 21 

done 

答えて

0

nc終了ステータスをテストできます。コマンドncが成功したと暗黙$?シェル変数に格納されているゼロの終了ステータス、exitスクリプトを返す場合

nc -w1 $GW$octet4 21 
[[ "$?" -eq 0 ]] && exit 

例:.:。ループから飛び出したい場合は、exitの代わりにbreakを使用してください。

0

ncの戻りコードを使用して0に等しいときに中断することができます。次に、googles DNSサーバーIP 8.8.8.8に感染するまで繰り返すスクリプトの例を示します。

#!/bin/bash 

for i in {1..10}; do 
    sleep 1; 
    echo Trying 8.8.8.$i 
    nc -w1 8.8.8.$i 53 
    if [ $? == 0 ]; then 
     break 
    fi 
done 

スクリプトは次のようになります。

#!/bin/bash 

#Find first 3 octets of the gateway and set it to a variable. 

GW=$(route -n | grep 'UG[ \t]' | awk '{print $2}' | cut -c1-10) 

#loop through 1 to 255 on the 4th octect 
for octet4 in {1..255} 
do 
     sleep .2 
     nc -w1 $GW$octet4 21 
     if [ $? == 0 ] 
     then 
      break 
     fi 
done 
関連する問題