Jul 132012

A one line gawk script to transfer a file to a waiting netcat… it’s sort of a really crappy one-way netcat that you stuff things into.   I actually sort of needed this when on a suxx0r really stripped down busybox linux system that had zero file transfer programs, it was a wasteland… but the fools left gawk on the system… so a quick hack to do file transfers:

 gawk -F "" 'BEGIN{RS="fizz-baz-baruu"; while (("/inet/tcp/'$1'/0/0" |& getline line) > 0) printf("%s", line); }'

(The RS=’weird string’ meansset the record sep to something that doesn’t exist; awk will then treat the whole file as a single record.  This is for the weirdness of binary data.  An edit from an earlier version.)

If that line were in a shell script you’d say:

foo-script host tcp-portnum file


foo-script 6666 /etc/passwd

And the netcat on would look like:

nc -l 6666

You cold also redirect it to a file if wanted:

nc -l 6666 > /tmp/foofile

Or heck, write a one line gawk to receive:

gawk -F "" 'BEGIN{RS="fizz-baz-baruu"}{printf("%s",$0) |& "/inet/tcp/0/'$1'/'$2'" }' $3

run like:

bar-script 6666

Or hell, a really crappy netcat, sends and receives data, in 5 lines (damn those conditionals, I could toss an exit or something in there to do it shorter :)):

# read
if test "$3X" == "X" ; then
gawk -F "" 'BEGIN{RS="fizz-baz-baruu"; while (("/inet/tcp/'$1'/0/0" |& getline line) > 0) printf("%s", line); }'
# write
gawk -F "" 'BEGIN{RS="fizz-baz-baruu"}{printf("%s",$0) |& "/inet/tcp/0/'$1'/'$2'" }' $3

This beauty is a complete send and receiver, sort of netcatish. Well, a really bad netcat… sends a file, recieves a file via TCP on a given port. To recieve; on the host you want data:

foobarscript port

To send; on the host you want to send data from:

foobarscript host port file

Of course, who needs error checking?

Gotta love awk (props to gawk for adding net stuff ;)).   Unix-like-systems can rock even if really minimal.  And if you want to keep systems locked down or users from doing things you don’t want, you really want to keep them off your systems entirely.

p.s. At times awk/gawk isn’t binary clean… but BWK writes in ;login:

A standard example is binary data, since Awk expects everything to be text; for example, Awk survives these two tests

	awk -f awk		 "program" is raw binary 
	awk '{print}' awk	 input data is raw binary 

by producing a syntax error as expected for the first and by quietly stopping after some early null byte in the input for the second. The program generally seems robust against this kind of assault, though it is rash to claim anything specific.

Non-POSIX systems might need a bit of help – in the gawk manual it says:

There’s an environment variable called BINMODE that:

On non-POSIX systems, this variable specifies use of binary mode for all I/O. Numeric
values of one, two, or three specify that input files, output files, or all files, respectively,
should use binary I/O.

Sorry, the comment form is closed at this time.