【问题标题】:Python 2.6 problem: Capturing output from tcpdump subprocessPython 2.6 问题:从 tcpdump 子进程捕获输出
【发布时间】:2011-08-25 16:38:46
【问题描述】:

我正在尝试从 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

【问题讨论】:

  • 你已经设置了sudo,所以它不会只是坐在那里等待密码?
  • 不,我正在通过 sudo 调用我的 python 脚本:sudo myScript.py
  • 如何将 'Host\: .*|GET \/.*' 更改为 '"'Host\: .*|GET \/.*"'?
  • Zaur:我试过你的建议,但没有效果。此外,我已经知道正则表达式是可以的。如果我省略 Popen 的“stdin=p1.stdout”参数,我可以看到 grep 输出正在打印到控制台。所以正则表达式很好。

标签: python macos subprocess nonblocking tcpdump


【解决方案1】:

试试

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

【讨论】:

  • 哦,祝福你。我应该知道的。
  • 这在 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
猜你喜欢
  • 2016-07-21
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 2011-11-28
  • 2017-09-17
  • 2018-04-12
相关资源
最近更新 更多