4

I have run into a problem where I have a ncat server with the command ncat -l [port] -k -c "cat > foo; cat > bar". When I connect to this server through netcat, it allows me to write to the file foo, and after that, bar. The problem is that when the client connecting wants to stop writing foo by sending a ^D, it closes the client instead of moving on to writing to bar, so bar is never written to. How can I bypass this? What's an alternative to cat that allows me to quit with a command instead of an EOF?

2

If what you want to do is transfer 2 files with only 1 connection, you will have to somehow use a marker to separate the files in the data stream, as end-of-file is a read of length 0 that netcat will use to close the socket.

Control-D may be what you can type in a terminal to signify end-of-file, but it does not generate a character, it terminates the read with a length of 0. There is no Control-D in the data stream.

To transfer 2 files simply, you could use an existing packaging command like tar. Use nc -k -l 4458 -v -c 'tar xf - >&2' as your receiver and tar cf - foo bar as your sender. (Since the filenames come from the sender you must trust the sender).

Alternatively, if your files are simple text you could introduce a special line to separate the 2 files. Eg at the sender cat foo; echo bye; cat bar and at the receiver something like

nc -k -l 4458 -v -c 'awk -v file=foo '\''/^bye$/{ file="bar";next }{print >file}'\'

This GNU awk script holds the first filename in variable file, then when it sees the "bye" line it changes to the second filename.

  • This is a very good answer, but I'm not sending files, I'm rather executing a remote script to a user that asks to make multiple file edits. Your AWK script is nice too, but I made my own bash script called catylist that is like a command oriented file editor and viewer. Your solution would have worked nicely if I got your post earlier. – SpecialBomb May 23 '16 at 14:44

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.