如何实时处理/管道 TCPDUMPs 输出

Lan*_*nes 29 pipe tcpdump

如果我想 tcpdump 客户端的 DNS 请求(在 OpenWrt 10.04 路由器上),那么我

root@ROUTER:/etc# tcpdump -n -i br-lan dst port 53 2>&1       
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on br-lan, link-type EN10MB (Ethernet), capture size 96 bytes
22:29:38.989412 IP 192.168.1.200.55919 > 192.168.1.1.53: 5697+ A? foo.org. (25)
22:29:39.538981 IP 192.168.1.200.60071 > 192.168.1.1.53: 17481+ PTR? 150.33.87.208.in-addr.arpa. (44)
^C
2 packets captured
3 packets received by filter
0 packets dropped by kernel
Run Code Online (Sandbox Code Playgroud)

那完全没问题。但。为什么我不能实时传输 tcpdumps 输出?

root@ROUTER:/etc# tcpdump -n -i br-lan dst port 53 2>&1 | awk '/\?/ {print $3}'
^C
root@ROUTER:/etc# 
Run Code Online (Sandbox Code Playgroud)

如果我在 tcpdump 之后执行 awk 等任何操作,我将不会得到任何输出。这是为什么?为什么我不能通过流水线实时处理 tcpdump 的输出?(例如:在示例中仅输出第三列)

有什么解决方案吗?

Mar*_*cin 39

直接出 man tcpdump

-l     Make stdout line buffered.  Useful if you want to see the data while 
       capturing it.  E.g.,

              tcpdump -l | tee dat

       or

              tcpdump -l > dat & tail -f dat

       Note that on Windows,``line buffered'' means ``unbuffered'', so that 
       WinDump will write each character individually if -l is specified.

       -U is similar to -l in its behavior, but it will cause output to be 
       ``packet-buffered'', so that the output is written to stdout at the 
       end of each packet rather than at the end of each line; this is 
       buffered on all platforms, including Windows.
Run Code Online (Sandbox Code Playgroud)


小智 7

将该选项-U与 结合使用,-w以便 tcpdump 立即写入数据包。