Abdoulaye Touré
Retour aux articles

Automatisation des Tests de Sécurité avec Python

4 min

Des scripts concis peuvent accélérer vos audits et réduisent les erreurs manuelles. Voici des snippets réutilisables et patterns testés en production.

Découverte réseau (async)

# Découverte ICMP/TCP en async (extrait)
import asyncio, ipaddress, socket

async def ping(host: str) -> bool:
    proc = await asyncio.create_subprocess_exec(
        "ping", "-c", "1", "-W", "1", host, stdout=asyncio.subprocess.DEVNULL
    )
    await proc.communicate()
    return proc.returncode == 0

async def scan_cidr(cidr: str):
    net = ipaddress.ip_network(cidr, strict=False)
    tasks = [ping(str(ip)) for ip in net.hosts()]
    results = await asyncio.gather(*tasks)
    return [str(ip) for ip, ok in zip(net.hosts(), results) if ok]

if __name__ == "__main__":
    alive = asyncio.run(scan_cidr("10.10.0.0/24"))
    print(alive)

Parsing Nmap XML → dict

import xml.etree.ElementTree as ET

def parse_nmap_xml(path: str):
    root = ET.parse(path).getroot()
    hosts = []
    for h in root.findall("host"):
        addr = h.find("address").get("addr")
        open_ports = []
        for p in h.findall(".//port"):
            if p.find("state").get("state") == "open":
                open_ports.append(int(p.get("portid")))
        hosts.append({"ip": addr, "open_ports": open_ports})
    return hosts

Générer un rapport Markdown

def to_markdown(hosts: list[dict]) -> str:
    lines = ["# Rapport Nmap", ""]
    for h in hosts:
        lines.append(f"## {h['ip']}")
        if h["open_ports"]:
            ports = ", ".join(map(str, h["open_ports"]))
            lines.append(f"Ports ouverts: **{ports}**")
        else:
            lines.append("Aucun port ouvert")
        lines.append("")
    return "\n".join(lines)

Envoi vers SIEM (Elasticsearch)

from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")

def send_to_es(index: str, doc: dict):
    es.index(index=index, document=doc)

# send_to_es("nmap-hosts", {"ip": "10.10.0.15", "open_ports": [22,80]})
SécuritéGérez vos secrets avec un vault ou variables d’environnement. Loggez les erreurs, versionnez vos requêtes et rapports.