Scapy 是一個(gè)可以讓用戶發(fā)送咸灿、偵聽和解析并偽裝網(wǎng)絡(luò)報(bào)文的 Python 程序匪燕。這些功能可以用于制作偵測蕾羊、掃描和攻擊網(wǎng)絡(luò)的工具喧笔。
在 Python
代碼中可以通過 sniff
函數(shù)調(diào)用抓包分析,并對(duì)抓到的包進(jìn)行回調(diào)操作龟再。
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:抓取報(bào)的數(shù)量溃斋,設(shè)置為0時(shí)則一直捕獲
store:保存抓取的數(shù)據(jù)包或者丟棄,1保存吸申,0丟棄
offline:從pcap文件中讀取數(shù)據(jù)包梗劫,而不進(jìn)行嗅探,默認(rèn)為None
prn:為每個(gè)數(shù)據(jù)包定義一個(gè)回調(diào)函數(shù)截碴,通常使用lambda表達(dá)式來寫回調(diào)函數(shù)
filter:過濾規(guī)則梳侨,可以在里面定義winreshark里面的過濾語法,使用 Berkeley Packet Filter (BPF)語法日丹,具體參考:[http://blog.csdn.net/qwertyupoiuytr/article/details/54670477](http://blog.csdn.net/qwertyupoiuytr/article/details/54670477)
L2socket:使用給定的L2socket
timeout:在給定的事件后停止嗅探走哺,默認(rèn)為None
opened_socket:對(duì)指定的對(duì)象使用.recv進(jìn)行讀取
stop_filter:定義一個(gè)函數(shù),決定在抓到指定的數(shù)據(jù)之后停止
iface:指定抓包的網(wǎng)卡,不指定則代表所有網(wǎng)卡
filter 語法
type(定義了類型)
可選值:host, net, port, portrange
例如:
host hostnameA
net 172.31 //相當(dāng)于172.31.0.0/16,又例如:192.168.1相當(dāng)于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定義了網(wǎng)絡(luò)協(xié)議)
可選值:ether, fddi, tr, wlan, ip, ip6, arp, rarp, decnet, tcp, udp, icmp
(fddi, tr, wlan是ether的別名, 包結(jié)構(gòu)很類似)
例如:
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)
參考文獻(xiàn)
- Scapy’s documentation: https://scapy.readthedocs.io/en/latest/index.html
- Scapy 中文文檔: https://wizardforcel.gitbooks.io/scapy-docs/content/
- python scapy 網(wǎng)卡抓包: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 函數(shù)丙躏、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