From 5abc47480542085ad92024ccf4b36a53cb764ee6 Mon Sep 17 00:00:00 2001 From: Admin MPCZ Date: Tue, 28 Apr 2026 01:18:59 +0200 Subject: [PATCH] perf(qualys/agents): combine toutes les cmds en 1 seul channel SSH avec markers - evite Timeout opening channel sur PSMP --- app/services/realtime_audit_service.py | 43 +++++++++++++++++++------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/app/services/realtime_audit_service.py b/app/services/realtime_audit_service.py index 7be0db9..fbe91a6 100644 --- a/app/services/realtime_audit_service.py +++ b/app/services/realtime_audit_service.py @@ -931,19 +931,38 @@ def audit_qualys_agent_only(hostname): result["connection_method"] = f"{method} -> {target}" try: + # Toutes les commandes dans 1 seul script bash avec markers — 1 channel SSH unique. + # Evite le "Timeout opening channel" sur PSMP qui limite le nombre de channels. + combined_parts = [] for key, cmd in QUALYS_AGENT_CMDS.items(): - out = _run(client, cmd) - # Retry avec reconnect si Timeout opening channel (limite PSMP) - if out and ("timeout opening channel" in out.lower() or - "channel closed" in out.lower()): - try: - client.close() - except Exception: - pass - client = _connect(target, hostname) - if client: - out = _run(client, cmd) - result[key] = out or "(empty)" + combined_parts.append(f"echo '__SECTION_{key}_START__'") + combined_parts.append(cmd) + combined_parts.append(f"echo '__SECTION_{key}_END__'") + combined = "; ".join(combined_parts) + + # exec_command direct avec timeout plus long (60s) car script combiné = curl 5s + plusieurs commandes + try: + _, stdout_chk, _ = client.exec_command("id -u", timeout=5) + uid = stdout_chk.read().decode().strip() + full_cmd = combined if uid == "0" else "sudo bash -c '" + combined.replace("'", "'\"'\"'") + "'" + _, stdout, stderr = client.exec_command(full_cmd, timeout=60) + big_out = stdout.read().decode("utf-8", errors="replace") + err = stderr.read().decode("utf-8", errors="replace") + if not big_out.strip() and err.strip(): + # Fallback retry sans sudo si sudoers refuse + _, stdout2, _ = client.exec_command(combined, timeout=60) + big_out = stdout2.read().decode("utf-8", errors="replace") + except Exception as ex_inner: + big_out = f"ERROR: {ex_inner}" + # Parser la sortie en cherchant les markers + for key in QUALYS_AGENT_CMDS: + start_marker = f"__SECTION_{key}_START__" + end_marker = f"__SECTION_{key}_END__" + try: + section = big_out.split(start_marker, 1)[1].split(end_marker, 1)[0].strip() + except Exception: + section = "(parsing failed)" + result[key] = section or "(empty)" result["status"] = "OK" except Exception as e: result["status"] = "ERROR"