Reputation: 3543
I'm using scapy
with python
to sniff live traffic.
capture=sniff(iface="<My Interface>", filter="tcp")
But this sniffs each packet and adds it to the list capture
which can be processed later.
I want to process a packet and display few fields of the packet, as soon as it's sniffed. i.e. upon sniffing a packet, it'll trigger a function where I can analyse that packet. And this would continue for few packets.
I've the function ready which I'm using with the captured packet list. But I'm unable to use it for each live packet.
How to achieve that? Is it possible with scapy
or do I need to install any other package?
Upvotes: 13
Views: 51543
Reputation: 3543
The parameters to the sniff function should be like the below code.:
from scapy.all import *
def pkt_callback(pkt):
pkt.show() # debug statement
sniff(iface="<My Interface>", prn=pkt_callback, filter="tcp", store=0)
store=0
says not to store any packet received and prn
says send the pkt
to pkt_callback
.
As mentioned by Yoel, if only one action is required, lambda
can be used with prn
instead of a new function like in this case:
sniff(iface="<My Interface>", prn = lambda x: x.show(), filter="tcp", store=0)
Upvotes: 17
Reputation: 9614
This can be done with the prn
argument of the sniff
function. Scapy
's tutorial has a simple example here. Scapy
's official API documentation specifies:
sniff(prn=None, lfilter=None, count=0, store=1, offline=None, L2socket=None, timeout=None)
...
prn
: function to apply to each packet. If something is returned, it is displayed. For instance you can useprn = lambda x: x.summary()
.
...
EDIT:
The accepted answer claims that the store
argument must be set to 0
for the prn
callback to be invoked. However, setting store=0
doesn't have any such effect. Scapy
's own examples don't set store=0
and the official API documentation doesn't mention any such requirement. In fact, inspecting Scapy
's source code reveals no connection whatsoever between the store
and prn
arguments. Here is an excerpt of the relevant code block:
...
if store:
lst.append(p)
c += 1
if prn:
r = prn(p)
if r is not None:
print r
...
Executing a few simple test cases supports this finding as well.
Upvotes: 8