简体   繁体   中英

How to send a pyshark packet to specific network interface?

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 (eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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