11

I am sending text commands to a custom protocol TCP server. In the example below I send 2 commands and receive a response written back. It works as expected in telnet and netcat:

$ nc 192.168.1.186 9760
command1
command2
theresponse

not working when i tried in batch:

@echo off
cd..
cd C:\nc
nc 192.168.1.186 9760
00LI002LE99
end

Please help me on this.

Shiva
  • 441
  • 3
  • 6
  • 14
  • 1
    Please elaborate what "not working" means. What do you see happen, and what do you expect to happen? Put your commands in a file called "commands.txt" and then run `nc 192.168.1.186 9760 < "commands.txt"` – indiv Jan 15 '14 at 18:30

1 Answers1

15

When you run nc interactively, it takes input from standard input (your terminal), so you can interact with it and send your commands.

When you run it in your batch script, you need to feed the commands into the standard input stream of nc - just putting the commands on the following lines won't do that; it will try to run those as entirely separate batch commands.

You need to put your commands into a file, then redirect the file into nc:

nc 192.168.1.186 9760 < commands.txt

On Linux, you can use a "here document" to embed the commands in the script.

nc 192.168.1.186 9760 <<END
command1
command2
END

but I haven't found an equivalent for windows batch scripts. It's a bit ugly, but you could echo the commands to a temp file, then redirect that to nc:

echo command1^

command2 > commands.txt

nc 192.168.1.186 9760 < commands.txt

The ^ escape character enables you to put a literal newline into the script. Another way to get newlines into an echo command (from this question):

echo command1 & echo.command2 > commands.txt

Ideally we'd just pipe straight to nc (this isn't quite working for me, but I can't actually try it with nc at the moment):

echo command1 & echo.command2 | nc 192.168.1.186 9760
Community
  • 1
  • 1
DNA
  • 40,109
  • 12
  • 96
  • 136
  • You may be able to use something like an echo tool with newlines on Windows to pipe a short multiline list into netcat. It's also possible the destination system would accept the particular commands being used all on one line if separated with semicolons. – Chris Stratton Mar 20 '14 at 14:58
  • Have added a suggestion using a temp file - would be nice to do this with a pipe though. Good idea about semicolons. – DNA Mar 20 '14 at 15:00
  • I'd assumed so, but it's not working correctly for me (using `sort` command instead of `nc`, as I don't have `nc` installed on Windows), but will edit answer anyway... – DNA Mar 20 '14 at 15:11
  • Yes... windows seems to be broken (surprise!) Sorry about that. – Chris Stratton Mar 20 '14 at 15:29
  • Thank you @DNA for the answer ! – Lyes Jun 17 '20 at 09:30