Send Commands to socket using netcat
batch-file, netcat, shell, sockets, tcp
Solution
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
Problem
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.