如果 bash 中没有连接成功则停止脚本
Stop script if nc connetion succeded in bash
如果与 netcat 的连接成功,我该如何停止我的脚本?
例如,如果 Connection to 192.168.2.4 21 port [tcp/ftp] succeeded!
我不确定那串文本是什么。
#!/bin/bash
#Find first 3 octets of the gateway and set it to a variable.
GW=$(route -n | grep 'UG[ \t]' | awk '{print }' | 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
您可以测试 nc
退出状态。
例如:
nc -w1 $GW$octet4 21
[[ "$?" -eq 0 ]] && exit
如果命令 nc
成功并且 return 零退出状态隐式存储在 $?
shell 变量中,exit
脚本。或者如果你想跳出循环,只使用 break
而不是 exit
。
您可以使用 nc
中的 return 代码,然后在它等于 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 }' | 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
如果与 netcat 的连接成功,我该如何停止我的脚本?
例如,如果 Connection to 192.168.2.4 21 port [tcp/ftp] succeeded!
我不确定那串文本是什么。
#!/bin/bash
#Find first 3 octets of the gateway and set it to a variable.
GW=$(route -n | grep 'UG[ \t]' | awk '{print }' | 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
您可以测试 nc
退出状态。
例如:
nc -w1 $GW$octet4 21
[[ "$?" -eq 0 ]] && exit
如果命令 nc
成功并且 return 零退出状态隐式存储在 $?
shell 变量中,exit
脚本。或者如果你想跳出循环,只使用 break
而不是 exit
。
您可以使用 nc
中的 return 代码,然后在它等于 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 }' | 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