如何让python读取tcpdump用linux上的管道捕获的.pcap数据?

问题描述 投票:0回答:1

最近我设法将我的Raspberry Pi 3B + Board上的tcp数据捕获到本地机器上的Wireshark进行实时处理,但是现在我想用python实时捕获“TCP”部分中的“数据”列并发送数据列通过TCP端口到另一个应用程序侦听端口1234。

我想我试错了。我的尝试如下所示:

通过以下命令,wireshark可以实时分析另一台机器的tcp流。

ssh [email protected] tcpdump -ns 0 -i eth0 "not port 22" | wireshark -k -i -

它有效,而wireshark可以实时工作。我想在这些命令的基础上转储并显示符合我要求的每个数据包中的一些数据,所以我尝试过滤我想要的列:

ssh [email protected] tcpdump -ns 0 -i eth0 "not port 22" | python test.py

和文件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)

但只是无法显示任何东西。

顺便说一句,tcp流以二进制模式传输。

我想通过tcpdump实时(或90%实时)捕获tcp数据中的一些指定数据,但我尝试了一些方法并且不起作用。

我还尝试使用启用wireshark实时分析的命令,然后将数据转发到python脚本,我搜索谷歌2天,匹配零结果。

如果有人足够酷,可以帮助我吗?我将非常感激,谢谢!

python linux tcp wireshark tcpdump
1个回答
1
投票

这是一个如何管道到python脚本的简单示例。

import sys
import fileinput


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

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.
© www.soinside.com 2019 - 2024. All rights reserved.