- Programming/[02] Python

[python] pcap분석을 위한 dpkt 설치

n3015m 2016. 7. 4. 11:47

Python으로 pcap 파일을 분석하기 위해서 dpkt 라이브러리 설치가 필요합니다.



※ 설치방법


pip install dpkt




※ 사용법 기초


Pcap에서 datetime, mac address, ip.src, ip.dst, length을 출력하는 예제


import dpkt

import datetime

import socket


def mac_addr(address):

return ':'.join('%02x' % ord(b) for b in address)


with open('pcap파일명 입력', 'rb') as f:

pcap = dpkt.pcap.Reader(f)


var = 100


for timestamp, buf in pcap:

eth = dpkt.ethernet.Ethernet(buf)

ip = eth.data

var = var - 1

if var == 0:

break


if eth.type != dpkt.ethernet.ETH_TYPE_IP:

continue

   

if ip.p != dpkt.ip.IP_PROTO_TCP:

continue

print 'Timestamp: ', timestamp

print 'Ethernet Frame: ', mac_addr(eth.src), ' -> ', mac_addr(eth.dst), eth.type

print 'IP: %s -> %s len=%d \n' % (socket.inet_ntoa(ip.src), socket.inet_ntoa(ip.dst), ip.len)