python/scapy DNS sniffer and parser

大城市里の小女人 提交于 2019-12-04 17:57:33
>>> ls(DNS)
id         : ShortField           = (0)
qr         : BitField             = (0)
opcode     : BitEnumField         = (0)
aa         : BitField             = (0)
tc         : BitField             = (0)
rd         : BitField             = (0)
ra         : BitField             = (0)
z          : BitField             = (0)
rcode      : BitEnumField         = (0)
qdcount    : DNSRRCountField      = (None)
ancount    : DNSRRCountField      = (None)
nscount    : DNSRRCountField      = (None)
arcount    : DNSRRCountField      = (None)
qd         : DNSQRField           = (None)
an         : DNSRRField           = (None)
ns         : DNSRRField           = (None)
ar         : DNSRRField           = (None)
>>> ls(DNSQR)
qname      : DNSStrField          = ('.')
qtype      : ShortEnumField       = (1)
qclass     : ShortEnumField       = (1)
>>> ls(DNSRR)
rrname     : DNSStrField          = ('.')
type       : ShortEnumField       = (1)
rclass     : ShortEnumField       = (1)
ttl        : IntField             = (0)
rdlen      : RDLenField           = (None)
rdata      : RDataField           = ('')
>>> 

If the above layer definitions and fields are not enough, you can either define your own layer and decode the packet using your custom layer, or simply retrieve the data straight from the raw payload. As for the timestamp, you can do pkt.time.

I landed here while Googling scapy parse DNS queries (in my case i'm dealing with a captured pcap file)

this is my solution:

#!/usr/bin/env python

from scapy.all import *
from scapy.layers.dns import DNSRR, DNS, DNSQR

pcap = '/path/.../to/.../pcap/.../.pcap'
pkts = rdpcap(pcap)

for p in pkts:
    if p.haslayer(DNS):   
        if p.qdcount > 0 and isinstance(p.qd, DNSQR):
            name = p.qd.qname
        elif p.ancount > 0 and isinstance(p.an, DNSRR):
            name = p.an.rdata
        else:
            continue

        print name
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!