带连续管道的grep不起作用 [英] grep with continuous pipe does not work

查看:240
本文介绍了带连续管道的grep不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(也许是"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

但是我不能继续使用管道

but I can't continue to use pipe

不起作用(无输出)

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

当我将sudo tcpflow替换为cat foo.txt时,它会起作用:

When I replace sudo tcpflow with cat foo.txt, it works:

cat foo.txt | grep '^Host: ' | grep H

那么pipe或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 1 个字节块中,这是使用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 40961 byte chunks before sending to next command in pipeline, which is what overriden using stdbuf

1.将此很好的细节纳入主题.

1. Refer this nice detail into the subject.

这篇关于带连续管道的grep不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆