2016-11-24 30 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 -w1 $GW$octet4 21 
[[ "$?" -eq 0 ]] && exit 

如果命令nc成功並返回其隱含存儲在$? shell變量零個退出狀態,exit腳本。或者,如果您只想跳出循環,則只需使用break而不是exit

0

您可以使用nc中的返回碼,然後在它等於0時中斷。以下是一個示例腳本,該腳本可以進行迭代,直至遇到谷歌地圖服務器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