19

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.

1
  • 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" Commented Jan 15, 2014 at 18:30

1 Answer 1

27

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Have added a suggestion using a temp file - would be nice to do this with a pipe though. Good idea about semicolons.
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...
Yes... windows seems to be broken (surprise!) Sorry about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.