netcat 命令的结果不合逻辑地匹配字符串
我想测试哪个远程端口已打开,以了解我是否必须使用 telnet VNC Teamviewer 或其他设备进行连接。
我将有大约 10 个端口要测试,我正在为其编写一个脚本。 此时,我已经提供了以下代码:
function testPort(){
res=`nc -v $1 $2 < /dev/null`
echo $res
if [[ "$res" == *refused* ]]
then
echo "refused"
return 0
else
echo "accepted"
return 1
fi
}
if test -z "$1"
then
echo "What's the adress?"
read IP
else
IP="$1"
fi
testPort $IP 80
echo $res
的结果类似于:
nc: connect to 192.168.0.110 port 80 (tcp) failed: Connection refused
RFB 003.889 Connection to 192.168.0.110 5900 port [tcp/vnc-server] succeeded!
但在任何情况下,我都会显示“已接受”。我不明白为什么。有人可以解释我的错误在哪里吗?
I'm wanting to test wich distant port is open to know if I have to connect with telnet VNC Teamviewer or whatever.
I'll have about 10 ports to test, and I'm doing a script for it.
At this point I've come with this code:
function testPort(){
res=`nc -v $1 $2 < /dev/null`
echo $res
if [[ "$res" == *refused* ]]
then
echo "refused"
return 0
else
echo "accepted"
return 1
fi
}
if test -z "$1"
then
echo "What's the adress?"
read IP
else
IP="$1"
fi
testPort $IP 80
The result of echo $res
is something like:
nc: connect to 192.168.0.110 port 80 (tcp) failed: Connection refused
RFB 003.889 Connection to 192.168.0.110 5900 port [tcp/vnc-server] succeeded!
But in any case I got the "accepted" displayed. I can't figure out why. Can someone explain me where's my mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为 netcat 将其消息写入标准错误,而不是标准输出。因此,变量
res
为空,并且与*refused*
不匹配。您在控制台上看到 netcat 消息的原因不是因为
echo $res
行,而是因为您没有捕获标准错误,因此它会发送到控制台。如果将
testPort
的第一行更改为:它应该可以工作。
It's because netcat writes its message to standard error, not standard output. So, the variable
res
is empty, and doesn't match*refused*
.The reason you see the netcat message on the console is not because of the
echo $res
line, but because you aren't capturing standard error, so it's going to the console.If you change the first line of
testPort
to:It should work.