在python中处理tcpdump输出 [英] Handling tcpdump output in python

查看:459
本文介绍了在python中处理tcpdump输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中处理tcpdump输出.

Im trying to handle tcpdump output in python.

我需要运行tcpdump(捕获数据包并向我提供信息)并读取输出并进行处理.

What I need is to run tcpdump (which captures the packets and gives me information) and read the output and process it.

问题在于tcpdump会永远运行,我需要在输出后立即读取数据包信息并继续进行操作.

The problem is that tcpdump keeps running forever and I need to read the packet info as soon as it outputs and continue doing it.

我尝试研究python的子进程,并尝试使用popen调用tcpdump并传递标准输出,但这似乎不起作用.

I tried looking into subprocess of python and tried calling tcpdump using popen and piping the stdout but it doesnt seem to work.

有关如何进行此操作的任何说明.

Any directions on how to proceed with this.

import subprocess

def redirect():
    tcpdump = subprocess.Popen("sudo tcpdump...", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    while True:
        s = tcpdump.stdout.readline()
        # do domething with s

redirect()

推荐答案

您可以使tcpdump以"-l"行缓冲.然后,您可以使用子过程捕获输出结果.

You can make tcpdump line-buffered with "-l". Then you can use subprocess to capture the output as it comes out.

import subprocess as sub

p = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
    print row.rstrip()   # process here

这篇关于在python中处理tcpdump输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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