How to display nc return value in Linux shell script?

孤街醉人 提交于 2019-12-10 19:39:32

问题


I am using nc command in my Linux box like below to check if a port is listening;

This displays success message:

nc -z 192.168.0.2 9000

This displays 0:

echo $?

I have combined it in a shell script .sh file like below;

#!/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;

#!/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?


回答1:


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

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.




回答2:


Your script works as expected for me. (Using nc 0.7.1 and sh 4.4.12)

Both, on command line as well as a script using #!/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.



来源:https://stackoverflow.com/questions/42377276/how-to-display-nc-return-value-in-linux-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!