queue.get()只返回一个项目

时间:2015-12-09 13:31:39

标签: python queue scapy python-multithreading

我正在构建一个小嗅探器,以便在我的网络中接收设备的答案。我宁愿通过实现Scapys Packet类的answers()方法来解决问题,但这并不能按预期工作。我试图通过首先创建一个嗅探线程,然后将数据包发送到设备并等待答案来绕过这一点。

import threading
from scapy.all import sniff
class SnifferThread(threading.Thread):

    """ Thread that sniffs for incoming packets
    """

    def __init__(self, queue, timeout=1, checkFunction=None, filter=None):
        """ Initialization method """
        if queue is None:
            raise Exception, "queue must not be None"

        self.q = queue
        self.filter = filter
        self.timeout = timeout
        self.checkFunction = checkFunction

        threading.Thread.__init__(self)


    def putInQueue(self, packet):
        """ Checks packet and puts it into the queue if it matches """
        if self.checkFunction:
            if self.checkFunction(packet):
                self.q.put(packet)
                print "put"
        else:
            self.q.put(packet)


    def run(self):
        """ Executes the sniffing """
        sniff(
            timeout=self.timeout,
            filter=self.filter,
            prn=lambda pkt: self.putInQueue(pkt)
        )

def has_IAm(packet):
    """ Checks whether the packet contains an IAm """
    if packet.haslayer(APDU):
        if (packet[APDU].serviceChoice\
                == BACNetAPDUUnconfirmedServiceChoice.I_AM):
            print "has I_AM"
            return True


def discoverDevices():
    """ Sends WhoIs packet and prints answers """

    bindBACNetLayers()

    myQ = Queue.Queue()

    sniffer = SnifferThread(
        queue=myQ,
        checkFunction=has_IAm,
        filter=FILTER_BACNET
    )
    sniffer.start()

    sendp(
        getBACNetWhoIsPacket(
            "192.168.1.1",
            "192.168.1.255"
        ),
        verbose=False
    )

    while sniffer.isAlive():
        print "still alive"
    print myQ.qsize()
    answers = PacketList()
    answers.append(myQ.get())

    answers.show()

discoverDevices()

执行它时,我可以在Wireshark中看到两个设备通过发送I_AM数据包进行响应。我还可以看到队列中有两个项目,因为最后print myQ.qsize()打印2。所以我希望myQ.get()返回两个数据包对象,然后在执行answers.show()时应该在终端中显示,但不知何故只显示一个数据包 - 第一个被接收的数据包。我错误地使用myQ.get()吗?

我解决了这个问题

while sniffer.isAlive():
    pass
answers = PacketList()
for _ in range(myQ.qsize()):
    answers.append(myQ.get())

1 个答案:

答案 0 :(得分:4)

get将始终返回单个项目,documentation表示:

  

从队列中删除并返回一个项目。

您应该反复调用get,直到队列为空。