Beispiel #1
0
def sniff(
    count=0,
    store=1,
    offline=None,
    prn=None,
    lfilter=None,
    L2socket=None,
    timeout=None,
    opened_socket=None,
    stop_filter=None,
    var_stop=False,
    *arg,
    **karg
):
    """Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets

	count: number of packets to capture. 0 means infinity
	store: wether to store sniffed packets or discard them
	prn: function to apply to each packet. If something is returned,
	     it is displayed. Ex:
	     ex: prn = lambda x: x.summary()
lfilter: python function applied to each packet to determine
	     if further action may be done
	     ex: lfilter = lambda x: x.haslayer(Padding)
offline: pcap file to read packets from, instead of sniffing them
timeout: stop sniffing after a given time (default: None)
L2socket: use the provided L2socket
opened_socket: provide an object ready to use .recv() on
stop_filter: python function applied to each packet to determine
	         if we have to stop the capture after this packet
	         ex: stop_filter = lambda x: x.haslayer(TCP)
	"""
    c = 0

    if opened_socket is not None:
        s = opened_socket
    else:
        if offline is None:
            if L2socket is None:
                L2socket = conf.L2listen
            s = L2socket(type=ETH_P_ALL, *arg, **karg)
        else:
            s = PcapReader(offline)

    lst = []
    if timeout is not None:
        stoptime = time.time() + timeout
    remain = None

    while 1 and not var_stop:
        try:
            if timeout is not None:
                remain = stoptime - time.time()
                if remain <= 0:
                    break
            sel = select.select([s], [], [], remain)
            if s in sel[0]:
                p = s.recv(MTU)
                if p is None:
                    break
                if lfilter and not lfilter(p):
                    continue
                if store:
                    lst.append(p)
                c += 1
                if prn:
                    r = prn(p)
                    if r is not None:
                        print r
                if stop_filter and stop_filter(p):
                    break
                if count > 0 and c >= count:
                    break
        except KeyboardInterrupt:
            var_stop = True
            break

    if opened_socket is None:
        s.close()
Beispiel #2
0
def sniff(count=0,
          store=1,
          offline=None,
          prn=None,
          lfilter=None,
          L2socket=None,
          timeout=None,
          opened_socket=None,
          stop_filter=None,
          var_stop=False,
          *arg,
          **karg):
    """Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets

	count: number of packets to capture. 0 means infinity
	store: wether to store sniffed packets or discard them
	prn: function to apply to each packet. If something is returned,
	     it is displayed. Ex:
	     ex: prn = lambda x: x.summary()
lfilter: python function applied to each packet to determine
	     if further action may be done
	     ex: lfilter = lambda x: x.haslayer(Padding)
offline: pcap file to read packets from, instead of sniffing them
timeout: stop sniffing after a given time (default: None)
L2socket: use the provided L2socket
opened_socket: provide an object ready to use .recv() on
stop_filter: python function applied to each packet to determine
	         if we have to stop the capture after this packet
	         ex: stop_filter = lambda x: x.haslayer(TCP)
	"""
    c = 0

    if opened_socket is not None:
        s = opened_socket
    else:
        if offline is None:
            if L2socket is None:
                L2socket = conf.L2listen
            s = L2socket(type=ETH_P_ALL, *arg, **karg)
        else:
            s = PcapReader(offline)

    lst = []
    if timeout is not None:
        stoptime = time.time() + timeout
    remain = None

    while 1 and not var_stop:
        try:
            if timeout is not None:
                remain = stoptime - time.time()
                if remain <= 0:
                    break
            sel = select.select([s], [], [], remain)
            if s in sel[0]:
                p = s.recv(MTU)
                if p is None:
                    break
                if lfilter and not lfilter(p):
                    continue
                if store:
                    lst.append(p)
                c += 1
                if prn:
                    r = prn(p)
                    if r is not None:
                        print r
                if stop_filter and stop_filter(p):
                    break
                if count > 0 and c >= count:
                    break
        except KeyboardInterrupt:
            var_stop = True
            break

    if opened_socket is None:
        s.close()
Beispiel #3
0
def sniff(
    store=False,
    prn=None,
    lfilter=None,
    stop_event=None,
    refresh=0.1,
    offline=None,
    *args,
    **kwargs
):
    """Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args)
Modified version of scapy.all.sniff

store : bool
    wether to store sniffed packets or discard them

prn : None or callable
    function to apply to each packet. If something is returned,
    it is displayed.
    ex: prn = lambda x: x.summary()

lfilter : None or callable
    function applied to each packet to determine
    if further action may be done
    ex: lfilter = lambda x: x.haslayer(Padding)

stop_event : None or Event
    Event that stops the function when set

refresh : float
    check stop_event.set() every `refresh` seconds
    """
    logger.debug("Setting up sniffer...")
    if offline is None:
        L2socket = conf.L2listen
        s = L2socket(type=ETH_P_ALL, *args, **kwargs)
    else:
        s = PcapReader(offline)

    # on Windows, it is not possible to select a L2socket
    if WINDOWS:
        from scapy.arch.pcapdnet import PcapTimeoutElapsed

        read_allowed_exceptions = (PcapTimeoutElapsed,)

        def _select(sockets):
            return sockets

    else:
        read_allowed_exceptions = ()

        def _select(sockets):
            try:
                return select(sockets, [], [], refresh)[0]
            except OSError as exc:
                # Catch 'Interrupted system call' errors
                if exc.errno == errno.EINTR:
                    return []
                raise

    lst = []
    try:
        logger.debug("Started Sniffing")
        while True:
            if stop_event and stop_event.is_set():
                break
            sel = _select([s])
            if s in sel:
                try:
                    p = s.recv(MTU)
                except read_allowed_exceptions:
                    # could add a sleep(refresh) if the CPU usage
                    # is too much on windows
                    continue
                if p is None:
                    break
                if lfilter and not lfilter(p):
                    continue
                if store:
                    lst.append(p)
                if prn:
                    r = prn(p)
                    if r is not None:
                        print(r)
    except KeyboardInterrupt:
        pass
    finally:
        logger.debug("Stopped sniffing.")
        s.close()

    return plist.PacketList(lst, "Sniffed")
Beispiel #4
0
def sniff(store=False, prn=None, lfilter=None,
          stop_event=None, refresh=.1, offline=None, *args, **kwargs):
    """Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args)
Modified version of scapy.all.sniff

store : bool
    wether to store sniffed packets or discard them

prn : None or callable
    function to apply to each packet. If something is returned,
    it is displayed.
    ex: prn = lambda x: x.summary()

lfilter : None or callable
    function applied to each packet to determine
    if further action may be done
    ex: lfilter = lambda x: x.haslayer(Padding)

stop_event : None or Event
    Event that stops the function when set

refresh : float
    check stop_event.set() every `refresh` seconds
    """
    logger.debug("Setting up sniffer...")
    if offline is None:
        L2socket = conf.L2listen
        s = L2socket(type=ETH_P_ALL, *args, **kwargs)
    else:
        s = PcapReader(offline)

    # on Windows, it is not possible to select a L2socket
    if WINDOWS:
        from scapy.arch.pcapdnet import PcapTimeoutElapsed
        read_allowed_exceptions = (PcapTimeoutElapsed,)

        def _select(sockets):
            return sockets
    else:
        read_allowed_exceptions = ()

        def _select(sockets):
            try:
                return select(sockets, [], [], refresh)[0]
            except select_error as exc:
                # Catch 'Interrupted system call' errors
                if exc[0] == errno.EINTR:
                    return []
                raise
    lst = []
    try:
        logger.debug("Started Sniffing")
        while True:
            if stop_event and stop_event.is_set():
                break
            sel = _select([s])
            if s in sel:
                try:
                    p = s.recv(MTU)
                except read_allowed_exceptions:
                    # could add a sleep(refresh) if the CPU usage
                    # is too much on windows
                    continue
                if p is None:
                    break
                if lfilter and not lfilter(p):
                    continue
                if store:
                    lst.append(p)
                if prn:
                    r = prn(p)
                    if r is not None:
                        print(r)
    except KeyboardInterrupt:
        pass
    finally:
        logger.debug("Stopped sniffing.")
        s.close()

    return plist.PacketList(lst, "Sniffed")