-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsers.py
72 lines (63 loc) · 2.19 KB
/
parsers.py
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
import json
import xml.etree.ElementTree as ET
from abc import ABC, abstractmethod
class PacketParser(ABC):
@abstractmethod
def parse(self, file_path):
pass
class JSONParser(PacketParser):
def parse(self, file_path):
with open(file_path, 'r') as file:
data = json.load(file)
return data
class XMLParser(PacketParser):
def parse(self, file_path):
tree = ET.parse(file_path)
root = tree.getroot()
return self._element_to_dict(root)
def _element_to_dict(self, element):
result = {}
for child in element:
if len(child) == 0:
result[child.tag] = child.text
else:
result[child.tag] = self._element_to_dict(child)
return result
class PlainTextParser(PacketParser):
def parse(self, file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return self._parse_lines(lines)
def _parse_lines(self, lines):
result = {}
for line in lines:
if ':' in line:
key, value = line.split(':', 1)
result[key.strip()] = value.strip()
return result
class PSMLParser(PacketParser):
def parse(self, file_path):
tree = ET.parse(file_path)
root = tree.getroot()
packets = []
for packet in root.findall('.//packet'):
packet_data = {}
for section in packet.findall('section'):
packet_data[section.get('name')] = section.text
packets.append(packet_data)
return packets
class PCAPNGParser(PacketParser):
def parse(self, file_path):
# This is a placeholder. Parsing pcapng files requires a specialized library.
print(f"Parsing pcapng file: {file_path}")
print("Note: Actual pcapng parsing not implemented. Consider using a library like 'scapy' for this.")
return {"warning": "pcapng parsing not implemented"}
def get_parser(file_format):
parsers = {
'json': JSONParser(),
'xml': XMLParser(),
'txt': PlainTextParser(),
'psml': PSMLParser(),
'pcapng': PCAPNGParser()
}
return parsers.get(file_format.lower())