萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

ngrep 實戰指南:網路層面的 grep 強力替代品

什麼是 ngrep?

ngrep = network grep。它基於 libpcap,支援 TCP/UDP/ICMP 封包擷取與模式比對,語法貼近 grep,適合快速偵錯 HTTP、DNS、SMTP 等明文協定流量。

安裝方式

git clone git://git.code.sf.net/p/ngrep/code ngrep-code
cd ngrep-code
./configure --with-pcap-includes=/usr/local/include/pcap
make && make install

或直接用套件管理器:yum install ngrep / apt-get install ngrep

核心參數速查表

參數說明
-q安靜模式,不顯示未匹配封包的 # 標記
-i忽略大小寫
-W byline解析封包中的換行符,輸出更易讀
-t每行前加時間戳
-T顯示與上一匹配封包的時間差
-d <dev>指定網卡介面(預設 pcap 自動選擇)
-n <num>僅擷取前 N 個封包
-O file.pcap將匹配封包存成 pcap 檔供 Wireshark 分析
-I file.pcap離線讀取 pcap 檔進行匹配

實戰範例

擷取所有 HTTP POST 請求

sudo ngrep -q -W byline '(POST).*'
interface: eth0 (192.168.122.0/255.255.254.0)
match: (POST).*
T 192.168.122.74:46048 -> 140.207.228.58:80 [A]
POST /Hotel/OTA_HotelSearch.asmx?wsdl HTTP/1.1
Content-Type: text/xml; charset=UTF-8
SOAPAction: https://ctrip.com/Request
...
<?xml version="1.0" encoding="utf-8"?><soap:Envelope ...><Request>...</Request></soap:Envelope>

擷取特定主機的 DNS 查詢

ngrep -q -d eth0 port 53 and host 8.8.8.8

離線分析 pcap 檔

ngrep -I capture.pcap -q 'password' -O leaked.pcap

進階技巧

  • 搭配 -x 以十六進位顯示二進位協定
  • 用 -A 5 在匹配後額外顯示 5 個封包,觀察回應內容
  • 配合 BPF 檔案 -F filter.bpf 複用複雜過濾規則

總結

ngrep 以 極低門檻 提供封包級關鍵字搜尋,是「不想開 Wireshark」時的最佳輕量替代方案。

copyright © 萬盛學電腦網 all rights reserved