Ref:
https://scapy.net/
https://github.com/secdev/scapy

Scapy: the Python-based interactive packet manipulation program & library.

It’s pretty easy to use scapy to generate frames/packets. I used it to test my devices for some disconnection case. I sent unicast/boradcasr ARP request/UDP packets to a WLAN interface. I’ll record how I use this tool in the following.

Install

Debian/Ubuntu
sudo apt install python-scapy

Sniffer

sniff(filter="",iface="any", prn=function, count=N)
  • filter的規則使用 Berkeley Packet Filter (BPF)語法
  • iface用來指定要在哪個網絡接口上進行
  • prn指定回調函數,每當一個符合filter的報文被探測到時,就會執行回調函數
    通常使用lambda表達式來寫回調函數
  • count指定最多嗅探多少個報文(是指符合filter條件的報文,而非所有報文
#example
sniff(filter="icmp", prn=lambda x:x.summary(), count=10)
Ether / IP / TCP 172.31.100.222:ssh > 172.31.100.149:57212 PA / Raw
Ether / IP / ICMP 172.31.100.149 > 172.31.100.222 echo-request 0 / Raw
Ether / IP / ICMP 172.31.100.222 > 172.31.100.149 echo-reply 0 / Raw

>>> pkt = sniff(filter="icmp", count=6)  //sniff 6 packets
>>> pkt.show() //show these 6 packets
0000 Ether / IP / TCP 192.168.199.1:2026 > 192.168.199.128:ssh A / Padding
0001 Ether / IP / ICMP 127.0.0.1 > 127.0.0.1 echo-request 0 / Raw
0002 Ether / IP / ICMP 127.0.0.1 > 127.0.0.1 echo-request 0 / Raw
0003 Ether / IP / ICMP 127.0.0.1 > 127.0.0.1 echo-reply 0 / Raw
0004 Ether / IP / ICMP 127.0.0.1 > 127.0.0.1 echo-reply 0 / Raw
0005 Ether / IP / ICMP 127.0.0.1 > 127.0.0.1 echo-request 0 / Raw

>>> pkt[5].show() //show packet[0005] in these packets
###[ Ethernet ]###
  dst= 00:00:00:00:00:00
  src= 00:00:00:00:00:00
  type= 0x800
...

>>> pkt[5].command() //transfer packet[0005] to command for sending
Ether(dst='ff:ff:ff:ff:ff:ff', type=2054, src='00:90:e8:cc:52:00')/ARP(ptype=2048, psrc='192.168.100.2', hwsrc='00:90:e8:cc:52:00', hwdst='00:00:00:00:00:00', hwlen=6, plen=4, hwtype=1, op=1, pdst='192.168.100.33')

Send

>>> sendp("I'm travelling on Ethernet", iface="eth1", loop=1, inter=0.2)

The send() function will send packets at layer 3.
The sendp() function will work at layer 2.

Leave a Reply

Close Menu