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


27

如果我想通过客户端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

没关系的 但。为什么我不能实时通过管道传输tcpdumps输出?

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

如果在tcpdump之后出现awk等问题,则不会得到任何输出。这是为什么?为什么不能通过流水线实时处理tcpdump的输出?(因此,例如:在示例中仅输出第三列)

有什么解决方案吗?

Answers:


35

直接出 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.


3

tcpdump写入管道时显然正在缓冲输出。它不是每次写入都刷新输出,因此系统将以大约4k字节的块写入输出。您的过滤器限制了输出,因此在该过滤器写入足够的输出之前您将看不到任何东西。一旦收集到足够多的内容,它将被分块地写出,然后您应该看到发出了几行。

尝试多次触发DNS查找,然后看看会发生什么。


1

expect有一个unbuffer命令可以欺骗命令,使其假定它们正在写入tty,因此不会缓冲。


1

我正在围绕tcpdump构建一个实时监视包装程序,该包装程序需要在数据包可用时立即查看它们。即使-l有一些延迟。

tcpdump现在具有--immediate-mode,它为我解决了这个问题。为了使其工作,我将其与配合使用-l

看到这个答案

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.