简体   繁体   English

如何使python在Linux上使用管道读取tcpdump捕获的.pcap数据?

[英]how to make python read .pcap data captured by tcpdump with pipe on linux?

Recently I manage to capture tcp data from my Raspberry Pi 3B+ Board to Wireshark on my local machine for realtime processing, but now I would like to capture the column "data" in "TCP" section with python in real time and send data of this columns via TCP port to another application listening on port 1234. 最近,我设法将Raspberry Pi 3B +板上的tcp数据捕获到本地计算机上的Wireshark进行实时处理,但是现在我想使用python实时捕获“ TCP”部分中的“数据”列并发送此数据列通过TCP端口连接到侦听端口1234的另一个应用程序。

I think I try in a wrong way. 我想我以错误的方式尝试。 My tries are shown below: 我的尝试如下所示:

the command below make wireshark can analysis the tcp stream of another machine in realtime. 下面的命令make wirehark可以实时分析另一台计算机的TCP流。

ssh root@10.0.1.2 tcpdump -ns 0 -i eth0 "not port 22" | wireshark -k -i -

it works, and wireshark can work in real-time. 它可以工作,wireshark可以实时工作。 I want to dump and display some data in every packet that match my requirement in terminal base on these command, so I try to filter my wanted column started by: 我想根据这些命令在每个数据包中转储并显示一些符合我在终端中要求的数据,因此我尝试过滤所需的列:

ssh root@10.0.1.2 tcpdump -ns 0 -i eth0 "not port 22" | python test.py

and file test.py as show below: 并文件test.py如下所示:

import sys
k = 0
try:
   for line in iter(sys.stdin.readline, b''):
      k = k + 1
      print(line)
except KeyboardInterrupt:
   sys.stdout.flush()
   pass
print(k)

but just can not display anything. 但只是什么也不能显示。

by the way, the tcp stream is transport in binary mode. 顺便说一下,tcp流是以二进制模式传输的。

I want to get some specified data in tcp data in real-time(or 90% real-time) capture by tcpdump, but I try some ways and won't work. 我想通过tcpdump实时(或90%实时)捕获tcp数据中的某些指定数据,但是我尝试了一些方法,但无法正常工作。

I also try to use the command that enable wireshark to analysis in real-time and then forward the data to python scripts, I search google for 2 days with zero results matched. 我还尝试使用启用wireshark进行实时分析的命令,然后将数据转发到python脚本,我在google中搜索了2天,结果匹配为零。

If anyone cool enough to help me with this? 如果有人愿意帮助我吗? I'll be very grateful, Thank you! 我将非常感谢,谢谢!

Here's a simple example of how to pipe to a python script. 这是一个如何通过管道传递到python脚本的简单示例。

import sys
import fileinput


incoming = fileinput.input(sys.argv[1:])
for line in incoming:
    print line.rstrip()

also python -u might help python -u也可能有帮助

-u     Force  stdin,  stdout  and  stderr to be totally unbuffered.  On
              systems where it matters, also put stdin, stdout and  stderr  in
              binary  mode.   Note  that there is internal buffering in xread‐
              lines(), readlines() and file-object  iterators  ("for  line  in
              sys.stdin")  which  is  not  influenced by this option.  To work
              around this, you will want to use "sys.stdin.readline()"  inside
              a "while 1:" loop.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM