Send Commands to socket using netcat
Asked Answered
D

1

18

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.

Divulge answered 15/1, 2014 at 6:45 Comment(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"Pseudohermaphroditism
P
26

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
Picklock answered 20/3, 2014 at 14:44 Comment(4)
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.Tobytobye
Have added a suggestion using a temp file - would be nice to do this with a pipe though. Good idea about semicolons.Picklock
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...Picklock
Yes... windows seems to be broken (surprise!) Sorry about that.Tobytobye

© 2022 - 2024 — McMap. All rights reserved.