首先用抓包工具抓包,保存为pcap文件。然后用python dpkt模块解析数据包,代码如下:
#coding=utf-8
import dpkt
import socket
import optparse
import datetime
def printPcap(pcap):
qqs=[]
#解析数据包
for (ts,buf) in pcap:
# print('Timestamp:',str(datetime.datetime.utcfromtimestamp(ts)))
try:
eth=dpkt.ethernet.Ethernet(buf)
# print('Ethernet Frame: ',eth.src,eth.dst,eth.type)
# if isinstance(eth.data,dpkt.qq.QQBasicPacket):
# print('Non QQ Packet type not supported %s\n' % eth.data.__class__.__name__)
# continue
ip=eth.data
#ip源地址和目的地址
src=socket.inet_ntoa(ip.src)
dst=socket.inet_ntoa(ip.dst)
#如果是UDP包,解析8000端口的数据包
if isinstance(ip.data,dpkt.udp.UDP):
udp=ip.data
if udp.sport == 8000 and udp.ulen>0:
# print(udp)
try:
#QQ数据包解析
request=dpkt.qq.QQBasicPacket(udp.data)
except (dpkt.dpkt.NeedData,dpkt.dpkt.UnpackError):
continue
# print('HTTP request:%s\n' % repr(request))
if '192.' in dst:
hostname_dst=socket.getfqdn(dst)
else:
hostname_dst=dst
if '192.' in src:
hostname_src=socket.getfqdn(src)
else:
hostname_src=src
#如果qq号不重复,打印QQ发送信息
if repr(request.qqNum) not in qqs:
print('IP:%s to---->IP:%s ----->QQ num:%s' % (hostname_src,hostname_dst,repr(request.qqNum)))
# print('QQ num:%s' % repr(request.qqNum))
qqs.append(repr(request.qqNum))
if udp.dport == 8000 and udp.ulen>0:
try:
request=dpkt.qq.QQBasicPacket(udp.data)
except (dpkt.dpkt.NeedData,dpkt.dpkt.UnpackError):
continue
if '192.' in dst:
hostname_dst=socket.getfqdn(dst)
else:
hostname_dst=dst
if '192.' in src:
hostname_src=socket.getfqdn(src)
else:
hostname_src=src
if repr(request.qqNum) not in qqs:
# print('HTTP request:%s\n' % repr(request))
print('IP:%s to---->IP:%s ----->QQ num:%s' % (hostname_src,hostname_dst,repr(request.qqNum)))
# print('IP2:%s ----->QQ num:%s ----->Host name:%s' % (src,repr(request.qqNum),hostname_src))
qqs.append(repr(request.qqNum))
except:
pass
def main():
parser=optparse.OptionParser('usage%prog -p <pcap file>')
parser.add_option('-p',dest='pcapFile',type='string',help='specify pcap filename')
(options,args)=parser.parse_args()
if options.pcapFile==None:
print(parser.usage)
exit(0)
pcapFile=options.pcapFile
#打开数据包pcap文件
f=open(pcapFile,'rb')
pcap=dpkt.pcap.Reader(f)
printPcap(pcap)
if __name__=='__main__':
main()
运行: python code.py -p data.pcap
结果如下:
转载于:https://blog.51cto.com/hackyao/2310744