当前位置:编程学习 > python >>

Python处理网络数据包示例(pcapy读pcap文件)

最近在围观python,找了个pcapy处理pcap数据的代码
 
非常非常久以前的东西了,应该是在项目组做的半成品吧。今天重装机器,不经意翻出来了。这个脚本是读入一个libpcap保存的文件,按照要求过滤数据,最后将过滤后的数据保存到一个新文件中。运行环境应该是2.5吧。
 
原文在http://muyublog.appspot.com/2010/08/31/python-pcapy.html
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/python
# Copyright (c) 2007
#
# Pcap dump file filter.
#
# This tools filter some packets in pcap capture files
# here is the packet send by our robot
#
# Authors:HonetNet Project
#
 
import sys
import string
from exceptions import Exception
import pcapy
from pcapy import *
 
def Drop(data):
    """Check if this packet should be drop
    """
    #return True
    return False
 
def filefilter(filename):
    """filter a single file
    """
    # Open file
    try:
        processor = open_offline(filename)
    except pcapy.PcapError, e:
        print "Can't open file: "+filename
        print "\t",e
        return 1
 
    #check if it's the Ether packet
    if pcapy.DLT_EN10MB != processor.datalink():
        print "Not a Ethernet packet..."
        return 2
 
    #Open the file store the data after filter
    if sys.platform == 'win32':
        pos = filename.rfind('\\')
    elif sys.platform == 'linux2':
        pos = filename.rfind('/')
    else:
        print "Running on a unexpect OS"
        sys.exit(1)
    if pos == -1:
        newfile = "filtered-"+filename
    else:
        newfile = filename[:pos+1] + 'filtered-' + filename[pos+1:]
    print newfile
    try:
        global dumper
        dumper = processor.dump_open(newfile)
    except pcapy.PcapError, e:
        print "Can't write packet to:", newfile
        print "\t",e
        return 3 www.zzzyk.com
    processor.loop(0, packetHandler)
 
def packetHandler(hdr, data):
    """process with single packet
    """
    if not Drop(data):
        global dumper
        dumper.dump(hdr, data)
 
# Process command-line arguments.
if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print "Usage: %s " % sys.argv[0]
        sys.exit(1)
    filefilter(sys.argv[1])
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,