2016-11-24 29 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