开发者

Result of netcat command illogically matching a string

开发者 https://www.devze.com 2023-03-24 07:12 出处:网络
I\'m wanting to test wich distant port is open to know if I have to connect with telnet VNC Teamviewer or whatever.

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

testP开发者_Python百科ort $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?


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:

    res=`nc -v $1 $2 < /dev/null 2>&1`

It should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号