【问题标题】:How to send a pyshark packet to specific network interface?如何将 pyshark 数据包发送到特定的网络接口?
【发布时间】:2019-02-23 00:38:17
【问题描述】:

我可以使用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'

谁能帮忙?

【问题讨论】:

    标签: python sockets pyshark


    【解决方案1】:

    我能够解决我的问题。解释如下:

    • 同时使用use_json=Trueinclude_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 ...
    

    【讨论】:

      最近更新 更多