问题描述
我在如下所示的Linux框中使用 nc
命令来检查端口是否在监听;
I am using nc
command in my Linux box like below to check if a port is listening;
这将显示成功消息:
nc -z 192.168.0.2 9000
这将显示0:
echo $?
我已将其组合到如下的shell脚本.sh文件中;
I have combined it in a shell script .sh file like below;
#!/bin/sh
nc -z 192.168.0.2 9000
echo $?
这将显示 1
,而不是预期的 0
.再说一次,如果我像下面那样修改脚本,它就会起作用;
This displays 1
instead of expected 0
. Again, if I modify my script like below, it works;
#!/bin/sh
echo nc -z 192.168.0.2 9000
echo $?
但是这里的问题是,它在类似的位置显示成功消息,然后在下一行显示0.我不想要成功消息,我期望为0.这是什么问题,我该如何解决?
But here the problem is, it displays success message on one like, then displays 0 in next line. I don't want success message, and I am expecting 0. What is wrong here and how can I fix this?
推荐答案
这个小脚本应该可以解决问题:
This small script should do the trick:
#!/bin/bash
SERVER=$1
PORT=$2
nc -z -v -G5 $SERVER $PORT &> /dev/null
result1=$?
#Do whatever you want
if [ "$result1" != 0 ]; then
echo port $PORT is closed on $SERVER
else
echo port $PORT is open on $SERVER
fi
用法:
./myscript.sh servername portnumber
例如:
./myscript www.google.com 80
www.google.com 80
port 80 is open on www.google.com
根据您使用的nc版本,您可能需要将-G调整为-w,因此请进行实验并找出最适合您的
Depending on the version of nc you're using, you may need to adjust the -G to -w, so experiment and find which works best for you.
这篇关于如何在Linux Shell脚本中显示nc返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!