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?
It’s because netcat writes its message to standard error, not standard output. So, the variable
resis empty, and doesn’t match*refused*.The reason you see the netcat message on the console is not because of the
echo $resline, but because you aren’t capturing standard error, so it’s going to the console.If you change the first line of
testPortto:It should work.