tcpdump 應該掌握的抓包技巧
tcpdump 是 Linux/Unix 系統的網絡抓包分析神器。它能像監控攝像頭一樣,實時捕獲流經網卡的數據包,并將這些二進制數據翻譯成可讀信息。無論是排查網絡故障、分析協議交互,還是安全檢測,它都是工程師工具箱里的“瑞士軍刀”。
一、語法
tcpdump [ -AbdDefhHIJKlLnNOpqStuUvxX# ] [ -B buffer_size ]
[ -c count ]
[ -C file_size ] [ -G rotate_seconds ] [ -F file ]
[ -i interface ] [ -j tstamp_type ] [ -m module ] [ -M secret ]
[ --number ] [ -Q|-P in|out|inout ]
[ -r file ] [ -V file ] [ -s snaplen ] [ -T type ] [ -w file ]
[ -W filecount ]
[ -E spi@ipaddr algo:secret,... ]
[ -y datalinktype ] [ -z postrotate-command ] [ -Z user ]
[ --time-stamp-precision=tstamp_precision ]
[ --immediate-mode ] [ --version ]
[ expression ]
二、常見參數
- -i:指定網卡(如 -i eth0),-i any 監聽所有接口
- -c:限制抓包數量(如 -c 100 捕獲100個包后停止)
- -s:設置抓包長度(-s 0 捕獲完整數據包)
- -w:保存到文件(如 -w capture.pcap)
- -d:把編譯過的數據包編碼轉換成可閱讀的格式
- -e:用來顯示源、目標ip的mac地址
- -r: 讀取文件分析
- -n:禁用域名解析,直接顯示IP
- -l:開啟行緩沖模式
- -A/-X:ASCII或十六進制格式顯示內容
三、過濾表達式
1. 主機、網絡與端口過濾:
- host:主機,如host 192.168.1.100
- net:網絡,如net 192.168.1.0/24
- port:端口,如port 80或port http
2. 協議過濾
tcp、udp、arp、rarp、icmp、ssh、telnet、ntp、ftp等等
3. 方向過濾
src、dst、src and dst、dst or src、in、out、inout
4. 邏輯組合
and/or/not(&& || !):如 src host 192.168.1.100 and dst port 443
四、場景舉例
抓包立即寫入磁盤:
tcpdump -i eth0 -U -w live.pcap
捕獲特定主機的HTTP/HTTPS流量:
tcpdump -i eth0 -n 'src host 192.168.1.1 and (dst port 80 or 443) and tcp'
抓取來自源地址為192.168.1.100的主機發送的icmp報文:
tcpdump -i eth0 -nn 'icmp and src host 192.168.1.100'
監控網卡 eth0,捕獲IP 192.168.1.100 發出的、基于TCP協議的、HTTP流量(端口80),直接顯示IP地址和端口號,并打印數據包中的明文內容:
tcpdump -i eth0 -nnA 'port 80 and tcp and src host 192.168.1.100'
1. -Q (--direction):流量方向控制
只抓取進入網卡的流量 (Inbound):
tcpdump -i eth0 -Q in -nn 'tcp port 22'
抓取發送到主機192.168.1.100的icmp報文:
tcpdump -i eth0 -Q out -nn 'host 192.168.1.100' and icmp
等同于:
tcpdump -i eth0 -nn 'dst host 192.168.1.100' and icmp
2. -tttt:打印完整可讀時間戳
捕獲ssh連接流量,并使用標準時間格式輸出:
tcpdump -tttt -i eth0 'port 22'
-e 用來顯示源、目標ip的mac地址:
tcpdump -i eth0 -e 'arp'
協議與端口組合,抓取端口80或443且協議為TCP的報文:
tcpdump -i eth0 -n 'tcp and (port 80 or port 443)' -vvv
3. -vvv:獲取更詳細的輸出信息
抓取TCP握手異常 (SYN無響應)的報文:
tcpdump -i eth0 -n 'tcp[tcpflags] & (tcp-syn) != 0 and tcp[tcpflags] & (tcp-ack) = 0'
實時提取IP地址為192.168.1.100的HTTP報文:
tcpdump -i eth0 -l -A -s0 'port 80' | grep -i '192.168.1.100'
捕獲進出IP為192.168.1.100的HTTPS流量,每文件100MB,保留最后10個文件,帶納秒時間戳:
tcpdump -i eth0 -Q inout -nn 'host 192.168.1.100 and port 443' \
-C 100 -W 10 -w https_trace.pcap \
--time-stamp-precision nano \
-z gzip # 自動壓縮完成文件
?? 趣味冷知識:tcpdump 誕生于 1987 年,比萬維網(WWW)還早 4 年!它的設計理念至今仍影響著現代網絡分析工具。