首页 > 解决方案 > 如何将 pyshark 数据包发送到特定的网络接口?

问题描述

我可以.pcap使用pyshark. 这是我的代码:

import pyshark
cap = pyshark.FileCapture(pcap_dir) # pcap_dir is the directory of my pcap file

print(cap[0]) # Print a packet
print(cap[0]['IP'].src) # Print some header value

现在,我需要将此数据包发送到某个接口(例如eth0)。我尝试了以下方法:

from socket import socket, AF_PACKET, SOCK_RAW
sock = socket(AF_PACKET, SOCK_RAW)
sock.bind(('eth0', 0))
sock.send(cap[0])

但我得到了错误:

    sock.send(cap[0])
TypeError: a bytes-like object is required, not 'Packet'

任何人都可以帮忙吗?

标签: pythonsocketspyshark

解决方案


我能够解决我的问题。这是解释:

  • 使用两者use_json=Trueinclude_raw=True能够获取原始数据包数据。
  • 如果您使用print(cap[0])打印第一个数据包,您应该看到一个带有 name 的层FRAME_RAW。这是包含整个数据包原始数据的层。

编码:

import pyshark
from socket import socket, AF_PACKET, SOCK_RAW

cap = pyshark.FileCapture(
                input_file=pcap_dir, # pcap_dir the pcap file directory
                use_json=True,
                include_raw=True
              )._packets_from_tshark_sync()

sock = socket(AF_PACKET, SOCK_RAW)
sock.bind(('YOUR_NETWORK_INTERFACE_NAME', 0))
sock.send(bytearray.fromhex(cap.__next__().frame_raw.value)) # 1st packet in the pcap file
sock.send(bytearray.fromhex(cap.__next__().frame_raw.value)) # 2nd packet in the pcap file
# And so on until the end of the file ...

推荐阅读