在 python3 scapy 模块中出现错误....数据包嗅探器

Getting error In python3 scapy Module .... Packet Sniffer

我正在使用 python-3.7 构建一个嗅探工具,当我尝试使用 scapy_http 模块时遇到了这个错误。

它在 python-2.x 中工作正常。对象类型为 packet[scapy.Raw].load

代码:

#!usr/bin/env python
import scapy.all as scapy
from scapy.layers import http

def sniff(interface):
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
    #store=Flase(does not store the output in memory)
    #prn= call another  function after one packet or any data is sniffed is sniffed

def process_sniffed_packet(packet):
    if packet.haslayer(http.HTTPRequest):
        if packet.haslayer(scapy.Raw):
            load = packet[scapy.Raw].load
            if "username" in load:
                print(load)
sniff("eth0")

错误:

 File "packet_sniffer.py", line 16, in <module>
    sniff("eth0")
  File "packet_sniffer.py", line 6, in sniff
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
  File "/usr/local/lib/python3.8/site-packages/scapy/sendrecv.py", line 1036, in sniff
    sniffer._run(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/scapy/sendrecv.py", line 989, in _run
    session.on_packet_received(p)
  File "/usr/local/lib/python3.8/site-packages/scapy/sessions.py", line 82, in on_packet_received
    result = self.prn(pkt)
  File "packet_sniffer.py", line 14, in process_sniffed_packet
    if "username" in load:
****TypeError: a bytes-like object is required, not 'str'****

packet[scapy.Raw].load 使用 scapy.packet.Raw class 中的 load。您要求 python 确定字符串是否在字节对象内,正如它所说,这是一个类型错误。很容易重现此错误:

>>> if "word" in b"word":
...     pass
...
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

尝试在第 14 行使用 if "username" in str(load):if b"username" in load:,这样就不会出现类型不匹配的情况。


注意:Class层次结构因您使用import scapy.all as scapy而混淆,因此scapy.Raw与[=17=相同] 在您的代码段中。