在 python 中处理 tcpdump 输出

Handling tcpdump output in python(在 python 中处理 tcpdump 输出)
本文介绍了在 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()

推荐答案

您可以使用-l"使 tcpdump 行缓冲.然后你可以使用 subprocess 来捕获输出.

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 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)