Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gmolveau
GitHub Repository: gmolveau/python_full_course
Path: blob/master/exercices/oop/multianalyzer/solution_multianalyzer_protocol.py
306 views
1
import functools
2
from dataclasses import dataclass
3
from typing import Protocol
4
5
6
@dataclass
7
class Result:
8
iocs: set[str]
9
score: int = 0
10
11
12
@dataclass
13
class Report:
14
results: list[Result] = None
15
16
@property
17
def score(self):
18
return functools.reduce(lambda x, y: x + y, (r.score for r in self.results))
19
20
@property
21
def iocs(self):
22
return sorted([ioc for r in self.results for ioc in r.iocs])
23
24
def __str__(self) -> str:
25
s = "Report :\n"
26
s += f"- score = {self.score}\n"
27
if self.iocs:
28
s += f"- iocs :\n"
29
for ioc in self.iocs:
30
s += f" - {ioc}\n"
31
return s
32
33
34
# correction Protocol
35
class Service(Protocol):
36
name: str
37
38
def run(self, filepath: str) -> Result:
39
raise NotImplementedError
40
41
42
@dataclass
43
class Yara:
44
name: str = "Yara"
45
46
def run(self, filepath: str) -> Result:
47
return Result(score=500, iocs=["1.1.1.1"])
48
49
50
@dataclass
51
class ScanPDF:
52
name: str = "ScanPDF"
53
54
def run(self, filepath: str) -> Result:
55
return Result(iocs=["cestpasnous.com"])
56
57
58
@dataclass
59
class Antivirus:
60
name: str = "Antivirus"
61
62
def run(self, filepath: str) -> Result:
63
return Result(score=500, iocs={})
64
65
66
@dataclass
67
class MultiAnalyzer:
68
services: list[Service]
69
70
def get_service_by_name(self, name: str) -> Service:
71
for service in self.services:
72
if service.name == name:
73
return service
74
raise ValueError
75
76
def analyze(self, filepath: str, services: list[str]) -> Report:
77
results = []
78
for service_name in services:
79
service = self.get_service_by_name(service_name)
80
results.append(service.run(filepath))
81
return Report(results=results)
82
83
84
scanpdf = ScanPDF()
85
yara = Yara()
86
antivirus = Antivirus()
87
tool = MultiAnalyzer(services=[scanpdf, yara, antivirus])
88
89
report = tool.analyze(filepath="bizarre.pdf", services=["ScanPDF", "Yara", "Antivirus"])
90
print(report)
91
assert (
92
str(report)
93
== """Report :
94
- score = 1000
95
- iocs :
96
- 1.1.1.1
97
- cestpasnous.com
98
"""
99
)
100
101