Python 2.6问题:捕获tcpdump子进程的输出

3

我试图从Python中捕获tcpdump/grep管道的输出。 我正在使用Mac OS 10.6.7上的Python 2.6。

当我尝试使用dmesg/grep时,调用者会收到来自子进程的输出,如预期所示。

但是,当我尝试使用tcpdump/grep时,select永远不会返回任何内容。

我做错了什么?

#! /usr/bin/python

def tcpdump():
    import subprocess, fcntl, os


    # This works

#   cmd1 = ['sudo', 'dmesg']
#   cmd2 = ['grep', '-E', '.*']


    # This doesn't work

    # sudo tcpdump -i en0 -n -s 0 -w - | grep -a -o -E "Host\: .*|GET \/.*"
    cmd1 = ['sudo', 'tcpdump', '-i', 'en0', '-n', '-s', '0', '-w', '-']
    cmd2 = ['grep', '-a', '-o', '-E', 'Host\: .*|GET \/.*']


    p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
    p2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stdin=p1.stdout)

    # set stdout file descriptor to nonblocking
    flags = \
    fcntl.fcntl(p2.stdout.fileno(), fcntl.F_GETFL)

    fcntl.fcntl(p2.stdout.fileno(), fcntl.F_SETFL, (flags | os.O_NDELAY | os.O_NONBLOCK))

    return p2


def poll_tcpdump(proc):
    import select

    txt = None

    while True:

        # wait 1/10 of a second and check whether proc has written anything to stdout
        readReady, _, _ = select.select([proc.stdout.fileno()], [], [], 0.1)

        if not len(readReady):
            break

        for line in iter(proc.stdout.readline, ""):

            if txt is None:
                txt = ''

            txt += line

        break

    return txt


proc = tcpdump()

while True:
    text = poll_tcpdump(proc)

    if text:
        print '>>>> ' + text

1
你已经设置好了 sudo,以便它不会只是坐在那里等待密码吗? - John Flatness
不,我是通过sudo调用我的Python脚本的:sudo myScript.py - mseery
把 'Host: .|GET /.' 改成 '"'Host: .|GET /."' 怎么样? - Zaur Nasibov
Zaur:我尝试了你的建议,但没有任何效果。此外,我已经知道正则表达式是正确的。如果我省略“stdin=p1.stdout”参数到Popen,我可以看到grep输出被打印到控制台。所以正则表达式没问题。 - mseery
1个回答

2

尝试

cmd2 = ['grep', '--line-buffered', '-a', '-o', '-E', 'Host\: .*|GET \/.*']

哦,谢谢你。我应该知道的。 - mseery
这在你的OS X上真的有效吗?在10.8.4,Python 2.7.4上,我得到了以下结果:File "./test.py", line 45, in poll_tcpdump for line in iter(proc.stdout.readline, ""): IOError: [Errno 35] Resource temporarily unavailable - iamtheneal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接