Use netcat as a proxy to log traffic
I want to use netcat as a proxy to log http requests and responses to files, then tail these to inspect traffic. Think wireshark.
Tried the following where 'fifo' is a named pipe, 'in' and 'out' are files, netcat proxy on port 8080, server on port 8081.
while true; do cat fifo | nc -l -p 8080 | tee -a in | nc localhost 8081 | tee -a out 1>fifo; done
Problems:
Netcat stop responing after first request (while loop ignored?).
Netcat fails with msg
localhost [127.0.0.1] 8081 (tproxy) : Connection refused
if server unavailable on 8081. Question: Is it possible to "lazily" connect to 8081 when request is made? I.e. I do not want to have 8081 running when netcat is started.
Solution 1:
ncat can do this quite easily, using the --sh-exec argument.
The following command will allow you to see both directions of a TCP connection live, and allows multiple connections. The connection to example.com
is done once for each connection received on localhost:8080
.
ncat -lkv localhost 8080 -c 'tee /dev/stderr | ncat -v example.com 80 | tee /dev/stderr'
Change the two tee
commands to tee -a ./file
if you wish to log to a file instead of displaying it live.
You can also remove the -v
to disable verbose output, leaving just the transfered data printed to the terminal.
-k, --keep-open Accept multiple connections in listen mode
-l, --listen Bind and listen for incoming connections
-v, --verbose Set verbosity level (can be used several times)
-c, --sh-exec <command> Executes the given command via /bin/sh
See ncat --help
or man ncat
for more details.
Solution 2:
Use socat, you don't need the pipes and fifos
Solution 3:
I'd use tcpdump (tutorial) for this. I think the command you want would look like this:
sudo tcpdump -i eth0 -s0 -v port 8080