bash 如何在 Linux shell 脚本中显示 nc 返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42377276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display nc return value in Linux shell script?
提问by blasteralfred Ψ
I am using nc
command in my Linux box like below to check if a port is listening;
我nc
在我的 Linux 框中使用如下命令来检查端口是否正在侦听;
This displays success message:
这将显示成功消息:
nc -z 192.168.0.2 9000
This displays 0:
这显示 0:
echo $?
I have combined it in a shell script .sh file like below;
我将它组合在一个 shell 脚本 .sh 文件中,如下所示;
#!/bin/sh
nc -z 192.168.0.2 9000
echo $?
This displays 1
instead of expected 0
. Again, if I modify my script like below, it works;
这将显示1
而不是预期的0
。同样,如果我像下面那样修改我的脚本,它就可以工作;
#!/bin/sh
echo nc -z 192.168.0.2 9000
echo $?
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?
但这里的问题是,它在一个喜欢上显示成功消息,然后在下一行显示 0。我不想要成功消息,我期待 0。这里有什么问题,我该如何解决?
回答by Dan
This small script should do the trick:
这个小脚本应该可以解决问题:
#!/bin/bash
SERVER=
PORT=
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
Usage:
用法:
./myscript.sh servername portnumber
For example:
例如:
./myscript www.google.com 80
www.google.com 80
port 80 is open on www.google.com
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.
根据您使用的 nc 版本,您可能需要将 -G 调整为 -w,因此请尝试并找出最适合您的版本。
回答by RuDevel
Your script works as expected for me. (Using nc 0.7.1 and sh 4.4.12)
您的脚本按我的预期工作。(使用 nc 0.7.1 和 sh 4.4.12)
Both, on command line as well as a script using #!/bin/sh
两者,在命令行以及使用脚本 #!/bin/sh
Just your last version - echo nc -z 192.168.0.2 9000
- does not execute nc at all but just echoes it out. Try replacing nc
with anything, e.g. ncc-1701
and you'll see what i mean.
只是你的最后一个版本 - echo nc -z 192.168.0.2 9000
- 根本不执行 nc 而只是将它回显出来。尝试用nc
任何东西替换,例如ncc-1701
,你就会明白我的意思。