如何将 pyshark 数据包发送到特定的网络接口?
How to send a pyshark packet to specific network interface?
我可以使用 pyshark
从 .pcap
文件中读取数据包。这是我的代码:
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'
有人能帮忙吗?
我能够解决我的问题。解释如下:
- 同时使用
use_json=True
和 include_raw=True
以获得原始数据包数据。
- 如果您使用
print(cap[0])
打印第一个数据包,您应该会看到一个名为 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 ...
我可以使用 pyshark
从 .pcap
文件中读取数据包。这是我的代码:
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'
有人能帮忙吗?
我能够解决我的问题。解释如下:
- 同时使用
use_json=True
和include_raw=True
以获得原始数据包数据。 - 如果您使用
print(cap[0])
打印第一个数据包,您应该会看到一个名为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 ...