Question: what does this command do?
# Don't do this nc localhost 12345 | sudo tar xf -
Answer: it sends the password typed into sudo to the other endpoint of netcat.
I can reproduce this with both nc.traditional and nc.openbsd.
One might be tempted to just put sudo in front of everything, but it'll mean that only nc will run as root:
# This is probably not what you want sudo nc localhost 12345 | tar xf -
The fix that I will never remember, thanks to twb on IRC, is to close nc's stdin:
<&- nc localhost 12345 | sudo tar xf -
Or flip the table and just use
$ sudo -s # nc localhost 12345 | tar xf -
Harald Koenig suggested two alternative spellings that might be easier to remember:
nc localhost 12345 < /dev/null | sudo tar xf - < /dev/null nc localhost 12345 | sudo tar xf -
And thinking along those lines, there could also be the disappointed face variant:
:| nc localhost 12345 | sudo tar xf -
Matthias Urlichs suggested the approach of
precaching sudo's credentials, making the rest of the command lines more
straightforward (and TIL:
sudo id nc localhost 12345 | sudo tar xf -
Or even better:
sudo id && nc localhost 12345 | sudo tar xf -
Shortcomings of nc | tar
Tomas Janousek commented:
There's one more problem with a plain tar | nc | tar without redirection or extra parameteres: it doesn't know when to stop. So the best way to use it, I believe, is:
tar c | nc -N
nc -d | tar x
-Noption terminates the sending end of the connection, and the
-doption tells the receiving netcat to never read any input. These two parameters, I hope, should also fix your sudo/password problem.
Hope it helps!