資源簡介
解析pcap數據包,提取出其中內容,http協議,https,icmp.dns
代碼片段和文件信息
#!/usr/bin/env?python
“““
此示例擴展了print_packets示例。?它檢查HTTP請求標頭并顯示其內容。
注意:我們沒有重建‘流‘,所以請求(如果你試圖解析它,則響應)只有在適合單個數據包時才能正確解析。
請求通常可以放在一個數據包中,但響應幾乎永遠不會。?為了正確重建流程,
您可能需要查看使用DPKT的其他項目(http://chains.readthedocs.io和其他)
“““
import?dpkt
import?datetime
import?socket
from?dpkt.compat?import?compat_ord
from?All_in?import?parse_http_total?as?pt
from?All_in?import?parse_http_detail?as?phd
from?All_in?import?feature_enginging?as?fe
from?All_in?import?add_detail?as?ad
from?All_in?import?add_total?as?at
import?traceback
import?time
def?mac_addr(address):
????“““Convert?a?MAC?address?to?a?readable/printable?string
???????Args:
???????????address?(str):?a?MAC?address?in?hex?form?(e.g.?‘\x01\x02\x03\x04\x05\x06‘)
???????Returns:
???????????str:?Printable/readable?MAC?address
????“““
????return?‘:‘.join(‘%02x‘?%?compat_ord(b)?for?b?in?address)
def?inet_to_str(inet):
????“““Convert?inet?object?to?a?string
????????Args:
????????????inet?(inet?struct):?inet?network?address
????????Returns:
????????????str:?Printable/readable?IP?address
????“““
????#?First?try?ipv4?and?then?ipv6
????try:
????????return?socket.inet_ntop(socket.AF_INET?inet)
????except?ValueError:
????????return?socket.inet_ntop(socket.AF_INET6?inet)
def?print_http_requests(pcapoutfile):
????“““Print?out?information?about?each?packet?in?a?pcap
???????Args:
???????????pcap:?dpkt?pcap?reader?object?(dpkt.pcap.Reader)
????“““
????#?For?each?packet?in?the?pcap?process?the?contents
????for?timestamp?buf?in?pcap:
????????#?Unpack?the?Ethernet?frame?(mac?src/dst?ethertype)
????????eth?=?dpkt.ethernet.Ethernet(buf)
????????#?Make?sure?the?Ethernet?data?contains?an?IP?packet
????????if?not?isinstance(eth.data?dpkt.ip.IP):
????????????print(‘Non?IP?Packet?type?not?supported?%s\n‘?%?eth.data.__class__.__name__)
????????????continue
????????#?Now?grab?the?data?within?the?Ethernet?frame?(the?IP?packet)
????????ip?=?eth.data
????????#?Check?for?TCP?in?the?transport?layer
????????if?isinstance(ip.data?dpkt.tcp.TCP):
????????????#?Set?the?TCP?data
????????????tcp?=?ip.data
????????????#?Now?see?if?we?can?parse?the?contents?as?a?HTTP?request
????????????#?response?=?dpkt.http.Response(temp.data)
????????????try:
????????????????#?request?=?dpkt.http.Request(tcp.data)
????????????????response?=?dpkt.http.Response(tcp.data)
????????????except?(dpkt.dpkt.NeedData?dpkt.dpkt.UnpackError):
????????????????try:
????????????????????#?response?=?dpkt.http.Response(tcp.data)
????????????????????request?=?dpkt.http.Request(tcp.data)
????????????????#?print(request.method)
????????????????#?print(request.uri)
????????????????#?print(request.headers[‘user-agent‘])
????????????????except?(dpkt.dpkt.NeedData?dpkt.dpkt.UnpackError):
????????????????????continue
????????????????continue
????????????#?Pull?out?fragment?information?(flags?and?offset?all?packed?into?off?field?so?use?bitmasks)
????????????do_not_fragment?=?bool
評論
共有 條評論