How to make Netcat return unused ports

I tried this command to try and find unused ports. What I want is to run netcat on a number of ports, find the ones that don't start services, grep the first of these lines of output, and then use sed to print only the port number.

nc -z <my url> 5000-5010 | grep -m 1 succeeded | sed 's/[^0-9]//g'

      

But when I try to start the service using the returned port, I get a message that the port is currently in use.

I found out that the success of netcat means the service is running on the port, but when I try that instead

nc -zv <my url> 5000-5010 | grep -m 1 failed | sed 's/[^0-9]//g'

      

I get nothing, although most of the output lines contain a word.

Going through the man pages showed that netcat -z only returns a result for successful results, although the reason why the line after a failed connection appears in my terminal window is still outside of me.

How can I use netcat to view the first port connected to?

+3


source to share


2 answers


The command nc -v

writes the failed / deleted messages to standard error rather than to standard output. You can redirect stderr to stdout with 2>&1

.

nc -zv <my url> 5000-5010 2>&1 | grep -m 1 failed

      

to get the bad line.

See http://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/



By the way, I suggest you use awk to get the port number from the output line:

nc -zv <my url> 5000-5010 2>&1 | grep -m 1 failed | awk '{print $6}'

      

which prints the value in the 6th column of the output line.

+1


source


To get a list of closed (unused) ports on a Linux system, you can use:

Real time output:

#!/bin/bash
remoteHost=stackoverflow.com
for i in {80..100}
do 
   nc -v -z -w 1 $remoteHost $i &> /dev/null && echo "Port $i Open" || echo "Port $i Closed" 
done

      

You can change the timeout currently set at 1 second ( -w 1

) to a higher value if needed.




Output:

Port 80 Open
Port 81 Closed
Port 82 Closed
Port 83 Closed
Port 84 Closed
Port 85 Closed
etc..

      




nc

arguments:

-v

Ask nc for more verbose output.

-z

Specifies that nc should just scan for listening to daemons without sending any data to them. Error using this option in combination with the -l option.

-w

timeout If the connection and stdin are idle for more than seconds, the connection is silently closed. The -w flag has no effect on the -l option, i.e. Nc will always listen for a connection, with or without the -w flag. There is no timeout by default.




Resources

nc man

+2


source







All Articles