Using Lamda functions with scapy

Another interesting feature of the sniff function is that it has the "prn" attribute, which allows us to execute a function each time a packet is captured. It is very useful if we want to manipulate and re-inject data packets:

scapy> packetsICMP = sniff(iface="eth0",filter="ICMP", prn=lambda x:x.summary())

For example, if we want capture n packets for the TCP protocol,we can do that with the sniff method:

scapy> a = sniff(filter="TCP", count=n)

In this instruction, we are capturing 100 packets for the TCP protocol:

scapy> a = sniff(filter="TCP", count=100)

In the following example, we see how we can apply custom actions on captured packets.We define a customAction method that takes a packet as a parameter. For each packet captured by the sniff function, we call this method and increment packetCount.

You can find the following code in the sniff_packets_customAction.py file:

import scapy module
from scapy.all import *

## create a packet count var
packetCount = 0
## define our custom action function
def customAction(packet):
packetCount += 1
return "{} {} {}".format(packetCount, packet[0][1].src, packet[0][1].dst)
## setup sniff, filtering for IP traffic
sniff(filter="IP",prn=customAction)

Also, we can monitor ARP packets with the sniff function and ARP filter.

You can find the following code in the sniff_packets_arp.py file:

from scapy.all import *

def arpDisplay(pkt):
if pkt[ARP].op == 1: #request
x= "Request: {} is asking about {} ".format(pkt[ARP].psrc,pkt[ARP].pdst)
print x
if pkt[ARP].op == 2: #response
x = "Response: {} has address {}".format(pkt[ARP].hwsrc,pkt[ARP].psrc)
print x

sniff(prn=arpDisplay, filter="ARP", store=0, count=10)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.218.157