依赖的包

$ pip install pcapy
$ pip install dpkt

测试程序

# -*- coding: utf-8 -*-
'''
Created on 2015年4月23日

@author: jilili
'''

import sys
import dpkt
import pcapy


devs = pcapy.findalldevs()
print "Devices List —>"
for i in devs:
    print "<%s>Dev:%s,Network:%s" %(devs.index(i),i,pcapy.open_live(i,0,0,0).getnet())
idx = raw_input("Your choice : ")
dev = devs[int(idx)]

# params:
# 1) device
# 2) snaplen (maximum number of bytes to capture _per_packet_)
# 3) promiscious mode (1 for true)
# 4) timeout (in milliseconds
p = pcapy.open_live(dev,1500,1,100)

# filter :
#   tcp and host 113.140.5.211
#   dst and host 113.140.5.211
#   host 113.140.5.211 and dst port 7974
p.setfilter('host 113.140.5.211 and dst port 7974')
print "Listening on %s" %dev

def pk(hdr, data):
    pkt = dpkt.ethernet.Ethernet(data)
    if pkt.data.__class__.__name__=='IP':
        ip_src = '%d.%d.%d.%d'%tuple(map(ord,list(pkt.data.src)))
        ip_dst = '%d.%d.%d.%d'%tuple(map(ord,list(pkt.data.dst)))
        src_port = '%d'%pkt.data.data.sport
        dst_port = '%d'%pkt.data.data.dport
        print ip_src + ":" + src_port, '>', ip_dst + ":" + dst_port
        print pkt.data.data.data, binascii.b2a_hex(pkt.data.data.data)
    else:
        print "Non-IP Protocol: ", pkt.data.__class__.__name__

def start():
    try:
        p.loop(0,pk)
    except KeyboardInterrupt:
        print "Terminated by user !"
        sys.exit(0)

if __name__ == '__main__':
    start()

[ 编辑 | 历史 ]
最近由“jilili”在“2016-01-05 07:10:51”修改