问题描述
(可能是tcpflow"的问题)
(maybe it is the "tcpflow" problem)
我写了一个脚本来监控http流量,我安装了tcpflow
,然后grep
I write a script to monitoring http traffic, and I install tcpflow
, then grep
它有效(并且您应该发出一个 http 请求,例如 curl www.163.com
)
it works (and you should make a http request, for example curl www.163.com
)
sudo tcpflow -p -c -i eth0 port 80 2>/dev/null | grep '^Host: '
它像这样(连续)输出
Host: config.getsync.com
Host: i.stack.imgur.com
Host: www.gravatar.com
Host: www.gravatar.com
但我不能继续使用管道
不起作用(无输出)
sudo tcpflow -p -c -i eth0 port 80 2>/dev/null | grep '^Host: ' | cut -b 7-
不起作用(无输出)
sudo tcpflow -p -c -i eth0 port 80 2>/dev/null | grep '^Host: ' | grep H
当我用 cat foo.txt
替换 sudo tcpflow
时,它可以工作:
When I replace sudo tcpflow
with cat foo.txt
, it works:
cat foo.txt | grep '^Host: ' | grep H
那么管道、grep 或 tcpflow 有什么问题?
so what's wrong with pipe or grep or tcpflow ?
更新:
这是我的最终脚本:https://github.com/zhengkai/config/blob/master/script/monitor_outgoing_http.sh
推荐答案
我认为问题出在 stdio buffering
,在调用grep
之前需要使用GNU stdbuf
,
I think the problem is because of stdio buffering
, you need to use GNU stdbuf
before calling grep
,
sudo tcpflow -p -c -i eth0 port 80 2>/dev/null | stdbuf -o0 grep '^Host: '
使用-o0
,它基本上意味着来自tcpflow
的输出(stdout
)流将是无缓冲的.默认行为是在发送到管道中的下一个命令之前自动将数据缓冲到 4096 字节块中,这是使用 stdbuf
With the -o0
, it basically means the output (stdout
) stream from tcpflow
will be unbuffered. The default behavior will be to automatically buffer up data into 4096 byte chunks before sending to next command in pipeline, which is what overriden using stdbuf
1. 参考这个不错的细节进入主题.
这篇关于带有连续管道的 grep 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!