1
2
3
4
5 """pcap_to_sqlite1
6
7 Generate the SQLite base from the pcap file.
8
9 Data extracted from the capture are :
10 - the timestamp ;
11 - destination address ;
12 - source address.
13
14 This script uses Pylibpcap which is faster than pcapy. So it is recommended to
15 use this script instead of using pcap_to_sqlite.py
16
17 http://sourceforge.net/projects/pylibpcap/
18
19 http://sourceforge.net/projects/pylibpcap/
20 """
21
22 __author__ = "Jerome Hussenet, Cedric Bonhomme"
23 __version__ = "$Revision: 0.3 $"
24 __date__ = "$Date: 2009/02/20 $"
25 __copyright__ = "Copyright (c) 2009 Jerome Hussenet, Copyright (c) 2009 Cedric Bonhomme"
26 __license__ = "Python"
27
28 import os
29 import sys
30 import pcap
31 import socket
32 import struct
33
34 import sqlite3
35
36
38 """Decode IP packets"""
39 d = {}
40
41
42
43
44
45
46
47
48
49
50 d['source_address'] = pcap.ntoa(struct.unpack('i',s[12:16])[0])
51 d['destination_address'] = pcap.ntoa(struct.unpack('i',s[16:20])[0])
52
53
54
55
56
57 return d
58
59
61 """Generate the SQLite base.
62
63 Read the pcap file given in parameter, extracts source and destination IP
64 and create the SQLite base.
65 """
66 reader = pcap.pcapObject()
67 reader.open_offline(pcap_file)
68
69 conn = sqlite3.connect(sqlite_file)
70 c = conn.cursor()
71
72 if options.verbose:
73 print "Creating table."
74 c.execute('''create table ip_link
75 (tts real, ip_src text, ip_dst text)''')
76
77 if options.verbose:
78 print "Reading pcap and inserting values in the table..."
79 while True:
80 try:
81 (_, payload, tts) = reader.next()
82 except:
83 break
84 if payload[12:14] == '\x08\x00':
85 decoded_ip_packet = decode_ip_packet(payload[14:])
86 c.execute('insert into ip_link values (?,?,?)', \
87 (str(tts), \
88 decoded_ip_packet['source_address'], \
89 decoded_ip_packet['destination_address']))
90
91 conn.commit()
92 c.close()
93
94
95 if __name__ == "__main__":
96
97 from optparse import OptionParser
98 parser = OptionParser()
99 parser.add_option("-i", "--input", dest="pcap_file",
100 help="pcap file")
101 parser.add_option("-o", "--output", dest="sqlite_file",
102 help="SQLite base to generate")
103 parser.add_option("-q", "--quiet",
104 action="store_false", dest="verbose",
105 help="be vewwy quiet (I'm hunting wabbits)")
106 parser.set_defaults(pcap_file = './captures/jubrowska-capture_1.cap',
107 sqlite_file = './data/ip.sql',
108 verbose = True)
109
110 (options, args) = parser.parse_args()
111
112 pcap_to_sqlite(options.pcap_file, options.sqlite_file)
113