Scapy 是一個可以讓用戶發送、偵聽和解析并偽裝網絡報文的 Python 程序。這些功能可以用于制作偵測、掃描和攻擊網絡的工具。
在 Python
代碼中可以通過 sniff
函數調用抓包分析,并對抓到的包進行回調操作。
Sniff
方法定義:
sniff(count=0,
store=1,
offline=None,
prn=None,
filter=None,
L2socket=None,
timeout=None,
opened_socket=None,
stop_filter=None,
iface=None)
count:抓取報的數量,設置為0時則一直捕獲
store:保存抓取的數據包或者丟棄,1保存,0丟棄
offline:從pcap文件中讀取數據包,而不進行嗅探,默認為None
prn:為每個數據包定義一個回調函數,通常使用lambda表達式來寫回調函數
filter:過濾規則,可以在里面定義winreshark里面的過濾語法,使用 Berkeley Packet Filter (BPF)語法,具體參考:[http://blog.csdn.net/qwertyupoiuytr/article/details/54670477](http://blog.csdn.net/qwertyupoiuytr/article/details/54670477)
L2socket:使用給定的L2socket
timeout:在給定的事件后停止嗅探,默認為None
opened_socket:對指定的對象使用.recv進行讀取
stop_filter:定義一個函數,決定在抓到指定的數據之后停止
iface:指定抓包的網卡,不指定則代表所有網卡
filter 語法
type(定義了類型)
可選值:host, net, port, portrange
例如:
host hostnameA
net 172.31 //相當于172.31.0.0/16,又例如:192.168.1相當于192.168.1.0/24
port 80
portrange 6000-6010
dir(direction,定義了傳輸方向)
可選值:src, dst, src or dst, src and dst
例如:
src net 172.31
src or dst port 21
proto(protocol定義了網絡協議)
可選值:ether, fddi, tr, wlan, ip, ip6, arp, rarp, decnet, tcp, udp, icmp
(fddi, tr, wlan是ether的別名, 包結構很類似)
例如:
ether src hostnameA
arp net 172.31
udp portrange 7000-8000
連接詞:and, or, not
例如:
tcp or udp
not icmp
示例代碼
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from scapy.all import *
def pack_callback(packet):
print ( packet.show() )
if packet['Ether'].payload:
print (packet['Ether'].src)
print (packet['Ether'].dst)
print (packet['Ether'].type)
if packet['ARP'].payload:
print (packet['ARP'].psrc)
print (packet['ARP'].pdst)
print (packet['ARP'].hwsrc)
print (packet['ARP'].hwdst)
time.sleep(2)
filterstr="arp"
sniff(filter=filterstr,prn=pack_callback, iface='eth0', count=0)
參考文獻
- Scapy’s documentation: https://scapy.readthedocs.io/en/latest/index.html
- Scapy 中文文檔: https://wizardforcel.gitbooks.io/scapy-docs/content/
- python scapy 網卡抓包:https://www.cnblogs.com/wangjq19920210/p/10089055.html
- Scapy Sniffer 的用法:https://blog.csdn.net/qwertyupoiuytr/article/details/54670489
- Scapy Sniffer 的 filter 語法:https://blog.csdn.net/qwertyupoiuytr/article/details/54670477
- lambda 函數、Scapy Sniffer 用法:https://zhuanlan.zhihu.com/p/42533185
- Python 變量類型:https://www.runoob.com/python/python-variable-types.html
- Python 字典(Dictionary): https://www.runoob.com/python/python-dictionary.html