4

I'm using nc to scan for open ports but I'm scanning a wide range and it's displaying too many results. Trying to grep it for the word "succeeded" doesn't work for some reason:

$ nc -zv localhost 31000-32000 | grep succeeded
...
nc: connect to localhost port 31957 (tcp) failed: Connection refused
nc: connect to localhost port 31958 (tcp) failed: Connection refused
nc: connect to localhost port 31959 (tcp) failed: Connection refused
Connection to localhost 31960 port [tcp/*] succeeded!
nc: connect to localhost port 31961 (tcp) failed: Connection refused
nc: connect to localhost port 31962 (tcp) failed: Connection refused
nc: connect to localhost port 31963 (tcp) failed: Connection refused
nc: connect to localhost port 31964 (tcp) failed: Connection refused
...

(I thought about sending the error messages to /dev/null as well: nc -zv localhost 31000-32000 2>/dev/null. But in that case there are no results whatsoever. It seems that all nc port status messages are error/debug messages)

1 Answer 1

13

nc writes its output to standard error, you need:

nc -zvv localhost 31000-32000 2>&1 | grep succeeded

The 2>&1 will redirect standard error to standard output so you can then pipe it to grep.

2
  • Why would it print to error??
    – Gerard
    Jan 21, 2020 at 12:50
  • 1
    @Gerard So as to not interfere with the data received from the server.
    – Kusalananda
    Jun 26, 2022 at 10:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .