Search code examples
batch-filenetcat

Using netcat in a batch file why the output remains in the console even when redirected?


I have a batch file and an excerpt of the code below. The code is used to test port on specific host.

The code shown below has an intentional error (wwww.google.com) that I am trying to redirect to a file for later treatment. Even if I redirect all outputs to the file the following is still shown in the console :

"wwww.google.com: forward host lookup failed: h_errno 11001: HOST_NOT_FOUND"

I would like to catch this error in the file rather than showing it to the console...Not sure why the redirects aren't working ?

@echo off
set tempFile=%temp%\temp

call :CheckPort "wwww.google.com" "80"
GOTO :EOF

:CheckPort
nc -z %~1 %~2^>%tempFile% 2^>^&1
EXIT /B 0

Solution

  • The escaping of the characters will break the pipe. instead do:

    nc -z %~1 %~2 > %tempFile% 2>&1
    

    which will redirect STDERR to STDOUT and STDOUT to file, meaning both will go to file.