0

I would like to check port connections with nc and forward the result to a text file.

stdout works fine. stderr is empty, if you don't use -v (which I dont want), so I would like to configure the error output like Servername: no connection

nc is version v1.10-41+b1.

Here's the command

nc -z -G 5 $Servername $Portname >> telnet_log.txt 2>&1
  • 1
    Can you provide an example of your situation, please. – roaima Nov 26 '19 at 11:37
  • My nc (v1.10-41+b1) prints this message to stderr. – Panki Nov 26 '19 at 11:39
  • Here's the command: nc -z -G 5 $Servername $Portname >> telnet_log.txt 2>&1 – stefan_parpart Nov 26 '19 at 11:44
1

nc on macOS exits with a non-zero exit status if it fails to connect to a host. You can use this fact in an if-statement to output an error message of your own:

if ! nc -z -G 5 "$server" "$port"; then
    printf '%s: no connection (port=%s)\n' "$server" "$port" >&2
fi >>nc-results.log 2>&1

This would add whatever data nc produces on standard output to the file nc-report.log if it succeeded in connecting, but would add your own custom error if it did not connect.

  • Thanks, this is much nicer than what I figured out meanwhile: nc -z -G 5 $Servername $Portname >> nc_log.txt 2>&1; if [ $? -ne 0 ]; then echo $Servername": No connection" >> $nc_log; fi – stefan_parpart Nov 26 '19 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.