~/netref / Scapy
##

Scapy

Python library to craft, send, sniff and dissect packets — stack layers with the / operator.

// core commands
IP(dst="192.0.2.1")Build an IP layer
IP()/TCP()/"data"Stack layers with /
send(pkt)Send at layer 3
sendp(Ether()/IP()…)Send at layer 2
sr1(IP()/ICMP())Send & receive first reply
sniff(count=100, iface="eth0")Capture packets
pkt.show()Display packet fields
ls(TCP)List a protocol's fields
fuzz(ICMP())Randomize fields

// notes

  • Python library to craft, send, sniff & dissect packets
  • RandIP() · RandMAC() · RandInt() generate random values
  • sr() = send + receive · srloop() loops and prints replies
  • Ideal for testing ACLs, IDS/IPS and protocol behaviour
// send / receive functions
sr(pkt)Send L3 + receive (answered, unanswered)
sr1(pkt)Send L3, return the first reply
srp(pkt)Send L2 + receive
send(pkt)Send L3, no reply expected
sendp(pkt)Send L2 (raw Ethernet)
sniff(...)Capture packets (filter=, prn=, count=)
rdpcap / wrpcapRead / write a .pcap file
traceroute(t)Built-in TCP traceroute

// worked examples

tcp syn scan
from scapy.all import *

# TCP SYN scan of one port
ans, unans = sr(IP(dst="192.0.2.10")/TCP(dport=443, flags="S"), timeout=2)
for snd, rcv in ans:
    print(rcv[TCP].flags)   # 'SA' = open, 'RA' = closed
arp ping a subnet
from scapy.all import *

# ARP ping a whole subnet (who is up?)
ans, _ = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"), timeout=2)
for snd, rcv in ans:
    print(rcv.psrc, rcv.hwsrc)
sniff dns
from scapy.all import *

# Sniff 10 DNS packets and print a summary
sniff(filter="udp port 53", count=10, prn=lambda p: p.summary())