How to send a pyshark packet to specific network interface?

你。 提交于 2019-12-08 05:11:27

问题


I am able to read a packet from .pcap file using pyshark. Here is my code:

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

Now, I need to send this packet to some interface (e.g. eth0 ). I tried the follwoing:

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

But I get the error:

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

Can anyone help?


回答1:


I was able to solve my problem. Here is the explanation:

  • Use both use_json=True and include_raw=True to be able to get the raw packet data.
  • If you use print(cap[0]) to print the first packet, you should see a layer with name FRAME_RAW. This is the layer that contains the whole packet raw data.

The code:

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 ...


来源:https://stackoverflow.com/questions/54837033/how-to-send-a-pyshark-packet-to-specific-network-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!