Compare commits

...

6 Commits

Author SHA1 Message Date
Chevallier
fea80315ef correction Equipement Stormshield 2026-01-19 14:17:53 +01:00
Chevallier
bb4de4e855 ajout name dans json, correction champ equipement matrice de routage, correction doublon headers matrice de routage 2026-01-16 14:57:51 +01:00
Chevallier
e4a906652d correction README.md 2026-01-15 15:28:02 +01:00
Chevallier
8314c18c0f correction parsing route Forcepoint 2026-01-15 13:54:56 +01:00
Chevallier
0079cbe738 correction output file name 2026-01-15 11:37:51 +01:00
Chevallier
52c1f73121 correction venv 2026-01-15 09:57:43 +01:00
9 changed files with 90 additions and 20 deletions

View File

@@ -50,10 +50,11 @@ Il founit également la possibilité de générer une **matrice de routage au fo
### Pré-requis ### Pré-requis
```bash ```bash
cd ..\..\
python -m venv .venv python -m venv .venv
.\.venv\Scripts\activate .\.venv\Scripts\activate
pip install -r .\src\requierements.txt pip install -r .\src\requirements.txt
``` ```
#### Commandes principales #### Commandes principales

View File

@@ -7,6 +7,15 @@ from scripts.json_Forcepoint import generate_json_forcepoint
from scripts.export_matrice_flux import export_to_excel as export_flux_to_excel from scripts.export_matrice_flux import export_to_excel as export_flux_to_excel
from scripts.export_matrice_routage import export_to_excel as export_routing_to_excel from scripts.export_matrice_routage import export_to_excel as export_routing_to_excel
def verify_if_file_exists(name):
base, ext = os.path.splitext(name)
counter = 1
new_name = name
while os.path.exists(new_name):
new_name = f"{base}_{counter}{ext}"
counter += 1
return new_name
def main(): def main():
if len(sys.argv) < 3: if len(sys.argv) < 3:
print("Usage: python3 src/main.py <firewall_type>[paloalto|stormshield|forcepoint] <input_directory/file> [-o <output_file>] [-f] [-r]") print("Usage: python3 src/main.py <firewall_type>[paloalto|stormshield|forcepoint] <input_directory/file> [-o <output_file>] [-f] [-r]")
@@ -21,6 +30,7 @@ def main():
input_data = sys.argv[2] input_data = sys.argv[2]
input_path = "src/input/" input_path = "src/input/"
output_path = "src/output/" output_path = "src/output/"
os.makedirs(output_path, exist_ok=True)
if "-o" in sys.argv: if "-o" in sys.argv:
o_index = sys.argv.index("-o") o_index = sys.argv.index("-o")
if o_index + 1 < len(sys.argv): if o_index + 1 < len(sys.argv):
@@ -31,7 +41,7 @@ def main():
else: else:
timestamp = time.strftime("%Y%m%d") timestamp = time.strftime("%Y%m%d")
output_file_json = f"{output_path}{firewall_type}_{timestamp}.json" output_file_json = f"{output_path}{firewall_type}_{timestamp}.json"
os.makedirs(output_path, exist_ok=True) output_file_json = verify_if_file_exists(output_file_json)
if firewall_type == "paloalto": if firewall_type == "paloalto":
generate_json_paloalto(input_data, output_file_json) generate_json_paloalto(input_data, output_file_json)
@@ -55,7 +65,7 @@ def main():
else: else:
timestamp = time.strftime("%Y%m%d") timestamp = time.strftime("%Y%m%d")
output_file_excel = f"{output_path}matrice_flux_{firewall_type}_{timestamp}.xlsx" output_file_excel = f"{output_path}matrice_flux_{firewall_type}_{timestamp}.xlsx"
output_file_excel = verify_if_file_exists(output_file_excel)
excel_file = export_flux_to_excel(output_file_json, output_file_excel) excel_file = export_flux_to_excel(output_file_json, output_file_excel)
print(f"✓ Processus terminé. Fichiers générés:\n - JSON: {output_file_json}\n - Excel: {excel_file}") print(f"✓ Processus terminé. Fichiers générés:\n - JSON: {output_file_json}\n - Excel: {excel_file}")
@@ -71,7 +81,7 @@ def main():
else: else:
timestamp = time.strftime("%Y%m%d") timestamp = time.strftime("%Y%m%d")
output_file_excel = f"{output_path}matrice_routage_{firewall_type}_{timestamp}.xlsx" output_file_excel = f"{output_path}matrice_routage_{firewall_type}_{timestamp}.xlsx"
output_file_excel = verify_if_file_exists(output_file_excel)
excel_file = export_routing_to_excel(output_file_json, output_file_excel) excel_file = export_routing_to_excel(output_file_json, output_file_excel)
print(f"✓ Processus terminé. Fichiers générés:\n - JSON: {output_file_json}\n - Excel: {excel_file}") print(f"✓ Processus terminé. Fichiers générés:\n - JSON: {output_file_json}\n - Excel: {excel_file}")

View File

@@ -44,6 +44,9 @@ def export_to_excel(json_file_path, output_file_excel):
for ni in network_instances: for ni in network_instances:
equipement = ni.get("name", "") equipement = ni.get("name", "")
fw_names = data.get("firewall-device", {}).get("name", [])
if equipement not in fw_names:
equipement = ", ".join(fw_names)
protocols = ni.get("protocols", {}).get("protocol", []) protocols = ni.get("protocols", {}).get("protocol", [])
for proto in protocols: for proto in protocols:
@@ -84,7 +87,7 @@ def export_to_excel(json_file_path, output_file_excel):
df = pd.DataFrame(rows) df = pd.DataFrame(rows)
with pd.ExcelWriter(output_file_excel, engine="openpyxl") as writer: with pd.ExcelWriter(output_file_excel, engine="openpyxl") as writer:
df.to_excel(writer,sheet_name="Routes statiques",index=False,startrow=1) df.to_excel(writer,sheet_name="Routes statiques",index=False,startrow=1,header=False)
wb = load_workbook(output_file_excel) wb = load_workbook(output_file_excel)
if "Sheet1" in wb.sheetnames: if "Sheet1" in wb.sheetnames:

View File

@@ -6,11 +6,12 @@ Fournit des méthodes communes pour la conversion et l'exportation des données
from typing import Dict, Any from typing import Dict, Any
class ParserMixin: class ParserMixin:
def to_openconfig_yang(self, type) -> Dict[str, Any]: def to_openconfig_yang(self, type, name) -> Dict[str, Any]:
"""Convertit la configuration au format OpenConfig YANG avec les nouveaux modèles""" """Convertit la configuration au format OpenConfig YANG avec les nouveaux modèles"""
openconfig = { openconfig = {
"firewall-device": { "firewall-device": {
"type": type "type": type,
"name": name
}, },
"openconfig-interfaces:interfaces": { "openconfig-interfaces:interfaces": {
"interface": [] "interface": []

View File

@@ -103,12 +103,43 @@ class ForcepointParser(ParserMixin):
self.config['interfaces'].append(Interface(name=name, ip=ip_addr, netmask=netmask, comment=comment)) self.config['interfaces'].append(Interface(name=name, ip=ip_addr, netmask=netmask, comment=comment))
def _parse_virtual_routers(self): def _parse_virtual_routers(self):
"""Parse routeurs simples""" """Parse les virtual routers avec interfaces et routes statiques"""
for router in self.root.findall(".//router"): for router in self.root.findall(".//routing_node"):
name = router.get("name") vr_name = router.get("name")
ip = router.find("mvia_address") interfaces = []
ip_addr = ip.get("address") if ip is not None else None static_routes = []
self.config['virtual_routers'].append(VirtualRouter(name=name, interfaces=[ip_addr] if ip_addr else [], static_routes=[]))
for iface in router.findall(".//interface_rn_level"):
iface_name = iface.get("name", None)
for network in iface.findall(".//network_rn_level"):
for gw in network.findall(".//gateway_rn_level"):
for ip_entry in gw.findall(".//ipaddress_behind_router"):
gw_ip = ip_entry.get("gateway")
ip_cidr = ip_entry.get("ipaddress")
static_routes.append(
StaticRoute(
name=f"{vr_name}_{ip_cidr}",
destination=ip_cidr,
metric=0,
next_hop_ip=gw_ip,
interface=iface_name
)
)
if gw_ip:
interfaces.append(gw_ip)
interfaces = list(set(interfaces))
self.config['virtual_routers'].append(
VirtualRouter(
name=vr_name,
interfaces=interfaces,
static_routes=static_routes
)
)
def _parse_security_rules(self): def _parse_security_rules(self):
"""Parse règles FW Forcepoint""" """Parse règles FW Forcepoint"""
@@ -158,7 +189,8 @@ class ForcepointParser(ParserMixin):
def export_to_json(self, output_file: str): def export_to_json(self, output_file: str):
"""Exporte la configuration au format JSON OpenConfig""" """Exporte la configuration au format JSON OpenConfig"""
openconfig_data = self.to_openconfig_yang("forcepoint") fw_names = [cluster.get("name") for cluster in self.root.findall(".//fw_cluster")]
openconfig_data = self.to_openconfig_yang("forcepoint", fw_names)
with open(output_file, 'w', encoding='utf-8') as f: with open(output_file, 'w', encoding='utf-8') as f:
json.dump(openconfig_data, f, indent=2, ensure_ascii=False) json.dump(openconfig_data, f, indent=2, ensure_ascii=False)

View File

@@ -451,7 +451,11 @@ class PaloAltoParser(ParserMixin):
def export_to_json(self, output_file: str): def export_to_json(self, output_file: str):
"""Exporte la configuration au format JSON OpenConfig""" """Exporte la configuration au format JSON OpenConfig"""
openconfig_data = self.to_openconfig_yang("palo-alto") fw_name = ""
deviceconfig = self.root.find(".//deviceconfig/system/hostname")
if deviceconfig is not None and deviceconfig.text:
fw_name = deviceconfig.text.strip()
openconfig_data = self.to_openconfig_yang("palo-alto", [fw_name])
with open(output_file, 'w', encoding='utf-8') as f: with open(output_file, 'w', encoding='utf-8') as f:
json.dump(openconfig_data, f, indent=2, ensure_ascii=False) json.dump(openconfig_data, f, indent=2, ensure_ascii=False)

View File

@@ -390,6 +390,18 @@ class StormshieldParser(ParserMixin):
self.config["security_rules"].append(rule) self.config["security_rules"].append(rule)
def _parse_name(self):
"""Parse le nom du firewall depuis le fichier network"""
path = os.path.join(self.base_dir, "network")
fw_name = ""
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
line = line.strip()
if line.startswith("Address="):
fw_name = line.split("=", 1)[1].strip()
break
return fw_name
def _extract_comment(self, line: str) -> str: def _extract_comment(self, line: str) -> str:
"""Extrait un commentaire après #""" """Extrait un commentaire après #"""
@@ -409,7 +421,7 @@ class StormshieldParser(ParserMixin):
def export_to_json(self, output_file: str): def export_to_json(self, output_file: str):
"""Exporte la configuration au format JSON OpenConfig""" """Exporte la configuration au format JSON OpenConfig"""
openconfig_data = self.to_openconfig_yang("stormshield") openconfig_data = self.to_openconfig_yang("stormshield", [self._parse_name()])
with open(output_file, 'w', encoding='utf-8') as f: with open(output_file, 'w', encoding='utf-8') as f:
json.dump(openconfig_data, f, indent=2, ensure_ascii=False) json.dump(openconfig_data, f, indent=2, ensure_ascii=False)

View File

@@ -76,7 +76,7 @@ def open_firewall_gui_multi(app, OUTPUT_DIR, HELP_FILE_FW, FIREWALL_DIR, FIREWAL
app2 = tk.Toplevel(app) app2 = tk.Toplevel(app)
app2.title("Analyse Configuration Firewall - Plusieurs firewall") app2.title("Analyse Configuration Firewall - Plusieurs firewall")
app2.geometry("800x450") app2.geometry("800x450")
app2.resizable(False, False) app2.resizable(True, True)
matrice_flux = tk.BooleanVar() matrice_flux = tk.BooleanVar()
matrice_routage = tk.BooleanVar() matrice_routage = tk.BooleanVar()
@@ -159,6 +159,13 @@ def open_firewall_gui_multi(app, OUTPUT_DIR, HELP_FILE_FW, FIREWALL_DIR, FIREWAL
if matrice_routage.get(): if matrice_routage.get():
cmd.append("-r") cmd.append("-r")
cmd.append("-o")
if item["type"] == "file":
base_name = os.path.splitext(item["name"])[0]
cmd.append(base_name)
else:
cmd.append(item["name"])
print("Commande exécutée :", " ".join(cmd)) print("Commande exécutée :", " ".join(cmd))
subprocess.run(cmd, cwd=FIREWALL_DIR, check=True) subprocess.run(cmd, cwd=FIREWALL_DIR, check=True)
@@ -412,7 +419,7 @@ def open_firewall_gui(root, BASE_DIR):
app = tk.Toplevel(root) app = tk.Toplevel(root)
app.title("Analyse Configuration Firewall") app.title("Analyse Configuration Firewall")
app.geometry("800x450") app.geometry("800x450")
app.resizable(False, False) app.resizable(True, True)
firewall_var = tk.StringVar() firewall_var = tk.StringVar()
input_var = tk.StringVar() input_var = tk.StringVar()

View File

@@ -8,7 +8,7 @@ from gui_firewall import open_firewall_gui
from gui_switch import open_switch_gui from gui_switch import open_switch_gui
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
VENV_DIR = os.path.join(BASE_DIR, "venv") VENV_DIR = os.path.join(BASE_DIR, ".venv")
REQ_FILE = os.path.join(BASE_DIR, "requirements.txt") REQ_FILE = os.path.join(BASE_DIR, "requirements.txt")
def venv_python(): def venv_python():
@@ -69,7 +69,7 @@ def open_main_gui():
root = tk.Tk() root = tk.Tk()
root.title("Analyse Réseau") root.title("Analyse Réseau")
root.geometry("650x350") root.geometry("650x350")
root.resizable(False, False) root.resizable(True, True)
ttk.Label( ttk.Label(
root, root,