# ================= SCRIPT D'EXEMPLE - LECTURE SEULE ================= # Ce script est identique a celui que vous recevrez, a deux valeurs pres : # VOTRE-PARC et JETON-PERSONNEL-VALABLE-1H (remplaces par les votres). # Il ne s'execute pas : utilisez la commande de votre tableau de bord. Write-Host "Script d'exemple : rien n'a ete installe." -ForegroundColor Yellow return # ==================================================================== # ================================================================= # Installation automatique Zabbix Agent 2 - Parc : VOTRE-PARC # LogiServ Monitoring | support@logiserv.app | logiserv.app # Zabbix Agent 2 7.4.16 | Windows x64 # ================================================================= # COMMENT EXÉCUTER : # 1. Ouvrez PowerShell en tant qu'administrateur # (Win+X -> Windows PowerShell (Admin)) # 2. Collez ce script et appuyez sur Entrée # ================================================================= # CE QUE FAIT CE SCRIPT (et rien d'autre) : # 1. Telecharge l'agent officiel Zabbix (logiciel open source, AGPLv3) # directement depuis les serveurs de Zabbix : # https://cdn.zabbix.com/zabbix/binaries/stable/7.4/7.4.16/zabbix_agent2-7.4.16-windows-amd64-openssl.msi # 2. Verifie la signature numerique du paquet (editeur "Zabbix SIA") et # s'arrete si elle est absente ou invalide. # 3. Enregistre ce systeme aupres de LogiServ en envoyant UNIQUEMENT : # le nom de l'ordinateur, le systeme ("windows") et la presence du # role Hyper-V. En retour : une cle de chiffrement unique (PSK). # 4. Installe l'agent sans regle de pare-feu (SKIP=fw) et ecrit sa # configuration : C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf # (l'ancienne configuration est sauvegardee en .bak). # 5. Ajoute le plugin open source ProcTop (licence MIT, code source : # https://github.com/logiserv/proctop-agent2-plugin), # apres verification de son empreinte SHA256 : il indique dans les alertes # quels processus consomment le CPU, la memoire ou le reseau. # 6. Demarre le service "Zabbix Agent 2". # CE QU'IL NE FAIT PAS : # - n'ouvre aucun port entrant (l'agent se connecte en sortie, 10051/TCP, # chiffre en TLS-PSK) ; # - ne cree ni compte utilisateur, ni tache planifiee, ni script annexe ; # - ne lit ni ne transmet vos fichiers ou documents. # DESINSTALLER A TOUT MOMENT (PowerShell administrateur) : # irm "https://www.logiserv.app/api/agent-uninstall/windows" | iex # Detail de ce que collecte l'agent : https://www.logiserv.app/confiance # ================================================================= #Requires -RunAsAdministrator $ErrorActionPreference = "Stop" $ProgressPreference = "SilentlyContinue" # Console en UTF-8 pour l'affichage correct des accents try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {} # #Requires est ignore quand le script est execute via "irm | iex" : controle explicite. $IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $IsAdmin) { Write-Host "" Write-Host "ERREUR : ce script doit etre lance dans un PowerShell ouvert en tant qu'administrateur." -ForegroundColor Red Write-Host "Clic droit sur Demarrer -> Terminal (Admin), puis collez a nouveau la commande." -ForegroundColor Yellow return } $swTotal = [System.Diagnostics.Stopwatch]::StartNew() Write-Host "" Write-Host "===================================================================" -ForegroundColor Cyan Write-Host " Installation Zabbix Agent 2 - Parc : VOTRE-PARC" -ForegroundColor Cyan Write-Host "===================================================================" -ForegroundColor Cyan Write-Host " Systeme : $env:COMPUTERNAME" Write-Host " Serveur : zabbix.logiserv.re" Write-Host " Agent : Zabbix Agent 2 7.4.16" Write-Host "-------------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " Deroulement (6 etapes) :" -ForegroundColor DarkGray Write-Host " 1.recherche version 2.enrolement 3.telechargement" -ForegroundColor DarkGray Write-Host " 4.installation 5.configuration 6.demarrage" -ForegroundColor DarkGray Write-Host " Les etapes 3 et 4 sont silencieuses (1-2 min possibles chacune)." -ForegroundColor DarkGray Write-Host " C'est normal : ne fermez pas la fenetre." -ForegroundColor DarkGray Write-Host "===================================================================" -ForegroundColor Cyan # -- Chemins -- $MsiUrl = "https://cdn.zabbix.com/zabbix/binaries/stable/7.4/7.4.16/zabbix_agent2-7.4.16-windows-amd64-openssl.msi" $ConfigDir = "C:\ProgramData\Zabbix" $ConfFile = "$ConfigDir\zabbix_agent2.conf" $PskFile = "$ConfigDir\zabbix_agent2.psk" $TempMsi = "$env:TEMP\zabbix_agent2.msi" $LogFile = "$env:TEMP\zabbix_install.log" # -- Détection et désinstallation de l'ancienne version -- # Le registre "Programmes et fonctionnalites" (Uninstall*) ne recense QUE les # installations faites via MSI/EXE. Un agent installe manuellement (zip + # "--install" comme service Windows, ou une installation anterieure a ce # script) n'y figure jamais alors que le service existe bel et bien -- d'ou # une detection complementaire via Get-Service, independante de la methode # d'installation d'origine. $regPaths = @( "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionUninstall*", "HKLM:SOFTWAREWOW6432NodeMicrosoftWindowsCurrentVersionUninstall*" ) $existing = $regPaths | ForEach-Object { Get-ItemProperty $_ -ErrorAction SilentlyContinue } | Where-Object { $_.DisplayName -like "Zabbix Agent*" } | Select-Object -First 1 $existingService = Get-Service -Name "Zabbix Agent 2" -ErrorAction SilentlyContinue if (-not $existingService) { $existingService = Get-Service -Name "Zabbix Agent" -ErrorAction SilentlyContinue } Write-Host "" Write-Host "[1/6] Recherche d'une version existante..." -ForegroundColor Cyan if ($existing) { Write-Host " Version $($existing.DisplayVersion) detectee, desinstallation en cours..." -ForegroundColor Yellow Stop-Service -Name "Zabbix Agent 2" -Force -ErrorAction SilentlyContinue Stop-Service -Name "Zabbix Agent" -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 $guid = $existing.PSChildName if ($guid -match "^{") { $proc0 = Start-Process "msiexec.exe" -ArgumentList "/x `"$guid`" /qn" -Wait -PassThru -ErrorAction SilentlyContinue if ($proc0.ExitCode -eq 0) { Write-Host " => Ancienne version désinstallée." -ForegroundColor Gray } Start-Sleep -Seconds 3 } } elseif ($existingService) { Write-Host " Service '$($existingService.Name)' detecte (installation non-MSI), arret en cours..." -ForegroundColor Yellow Stop-Service -Name "Zabbix Agent 2" -Force -ErrorAction SilentlyContinue Stop-Service -Name "Zabbix Agent" -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 Write-Host " => Service arrete, l'installation MSI va le remplacer." -ForegroundColor Gray } else { Write-Host " Aucune version presente, on continue." -ForegroundColor Gray } # -- Création des dossiers -- New-Item -ItemType Directory -Force -Path $ConfigDir | Out-Null New-Item -ItemType Directory -Force -Path "C:\zabbix\logs" | Out-Null # -- [2/6] Enrôlement auprès de LogiServ -- Write-Host "" Write-Host "[2/6] Enrolement du systeme aupres de LogiServ..." -ForegroundColor Cyan [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $EnrollUrl = "https://www.logiserv.app/api/agent-enroll" $EnrollToken = "JETON-PERSONNEL-VALABLE-1H" $MachineHostname = $env:COMPUTERNAME # Detection du role hyperviseur (Hyper-V) pour rattachement auto au groupe # Zabbix "Hyperviseurs" (seuils reseau DDOS/EXFILTRATION assouplis). $VmmsService = Get-Service -Name "vmms" -ErrorAction SilentlyContinue $IsHypervisor = [bool]($VmmsService -and $VmmsService.Status -eq "Running") # Poste de travail (Windows client : ProductType 1, contre 2-3 pour Windows Server) : eteint le # soir ou mis en veille, il recoit des alertes de disponibilite assouplies cote LogiServ. $OsInfo = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue $IsWorkstation = [bool]($OsInfo -and $OsInfo.ProductType -eq 1) Write-Host " Donnees envoyees : nom=$MachineHostname, systeme=windows, hyper-v=$IsHypervisor, poste=$IsWorkstation" -ForegroundColor Gray $EnrollBody = @{ token = $EnrollToken hostname = $MachineHostname os = "windows" rotateExisting = $true isHypervisor = $IsHypervisor isWorkstation = $IsWorkstation } | ConvertTo-Json -Compress try { $Enroll = Invoke-RestMethod -Method Post -Uri $EnrollUrl -ContentType "application/json" -Body $EnrollBody -TimeoutSec 30 } catch { Write-Host "" Write-Host "ERREUR : Échec de l'enrôlement auprès de LogiServ." -ForegroundColor Red Write-Host "" # Tenter de parser le message d'erreur JSON $resp = $_.Exception.Response $errorMessage = $null if ($resp) { try { $reader = New-Object System.IO.StreamReader($resp.GetResponseStream()) $errBody = $reader.ReadToEnd() $reader.Close() if ($errBody) { try { $errJson = $errBody | ConvertFrom-Json if ($errJson.error) { $errorMessage = $errJson.error } } catch { # Si le parsing JSON échoue, utiliser le body brut $errorMessage = $errBody } } } catch {} } # Afficher le message d'erreur extrait ou le message générique if ($errorMessage) { Write-Host "Message : $errorMessage" -ForegroundColor Yellow } else { Write-Host "Détail : $($_.Exception.Message)" -ForegroundColor Yellow } Write-Host "" Write-Host "Pour plus d'informations, consultez votre compte sur le portail LogiServ." -ForegroundColor Gray Write-Host "" pause exit 1 } if (-not $Enroll.psk) { Write-Host "ERREUR : Réponse d'enrôlement invalide (PSK manquante)." -ForegroundColor Red exit 1 } # -- Écriture de la clé PSK -- Set-Content -Path $PskFile -Value $Enroll.psk -Encoding ASCII -NoNewline Write-Host " OK - Hote enrole : $($Enroll.hostname)" -ForegroundColor Green # -- Gabarit de configuration (consommé par le MSI à l'installation) -- # Le MSI exige Server= dans son gabarit ; la conf réellement lue par le service # est réécrite à l'étape 5 en mode actif uniquement (sans Server=). if (Test-Path $ConfFile) { $stamp = Get-Date -Format "yyyyMMddHHmmss" Copy-Item $ConfFile "$ConfFile.bak.$stamp" -ErrorAction SilentlyContinue } @" Hostname=$($Enroll.hostname) TLSConnect=psk TLSAccept=psk TLSPSKFile=$PskFile TLSPSKIdentity=$($Enroll.pskIdentity) HostMetadata=$($Enroll.hostMetadata) Server=$($Enroll.serverActive) ServerActive=$($Enroll.serverActive) "@ | Set-Content -Path $ConfFile -Encoding ASCII # -- [3/6] Téléchargement du MSI -- Write-Host "" Write-Host "[3/6] Telechargement de l'agent Zabbix 7.4.16..." -ForegroundColor Cyan Write-Host " Quelques dizaines de Mo - peut prendre 1 a 2 min selon la connexion." -ForegroundColor Gray [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $swDl = [System.Diagnostics.Stopwatch]::StartNew() $dlOk = $false try { Import-Module BitsTransfer -ErrorAction Stop $ProgressPreference = "Continue" Start-BitsTransfer -Source $MsiUrl -Destination $TempMsi -DisplayName "Zabbix Agent 2" -Description "Telechargement en cours" $ProgressPreference = "SilentlyContinue" $dlOk = $true } catch { $ProgressPreference = "SilentlyContinue" Write-Host " (BITS indisponible, bascule sur telechargement direct...)" -ForegroundColor DarkGray } if (-not $dlOk) { Invoke-WebRequest -Uri $MsiUrl -OutFile $TempMsi -UseBasicParsing } $swDl.Stop() $sizeMo = [math]::Round((Get-Item $TempMsi).Length / 1MB, 1) Write-Host " OK - $sizeMo Mo telecharges en $([math]::Round($swDl.Elapsed.TotalSeconds,0)) s." -ForegroundColor Green # -- Verification de la signature Authenticode (editeur Zabbix SIA) -- # Un paquet altere ou non signe par Zabbix n'est jamais installe. $Sig = Get-AuthenticodeSignature -FilePath $TempMsi if ($Sig.Status -ne "Valid" -or -not $Sig.SignerCertificate -or $Sig.SignerCertificate.Subject -notmatch "O=Zabbix SIA") { Remove-Item $TempMsi -Force -ErrorAction SilentlyContinue Write-Host "ERREUR : la signature du paquet Zabbix est invalide ($($Sig.Status)). Installation annulee." -ForegroundColor Red Write-Host "Contactez support@logiserv.app." -ForegroundColor Yellow exit 1 } Write-Host " OK - Signature verifiee : $($Sig.SignerCertificate.Subject)" -ForegroundColor Green # -- [4/6] Installation -- Write-Host "" Write-Host "[4/6] Installation silencieuse en cours..." -ForegroundColor Cyan Write-Host " Aucune barre de progression (mode /qn) - ne fermez pas la fenetre." -ForegroundColor Gray $swInst = [System.Diagnostics.Stopwatch]::StartNew() # SKIP=fw : aucune règle d'exception n'est ajoutée au pare-feu Windows (mode # actif uniquement, l'agent n'écoute sur aucun port). $msiArgs = "/i `"$TempMsi`" /qn SKIP=fw NONMSICONFNAME=`"$ConfFile`" /l*v `"$LogFile`"" $proc = Start-Process -FilePath "msiexec.exe" -ArgumentList $msiArgs -Wait -PassThru $swInst.Stop() if ($proc.ExitCode -ne 0) { Write-Host "ERREUR : Installation échouée (code $($proc.ExitCode))." -ForegroundColor Red Write-Host "Consultez le log : $LogFile" -ForegroundColor Red exit 1 } Write-Host " OK - Agent installe en $([math]::Round($swInst.Elapsed.TotalSeconds,0)) s." -ForegroundColor Green # -- [5/6] Configuration définitive -- Write-Host "" Write-Host "[5/6] Ecriture de la configuration definitive..." -ForegroundColor Cyan # -- Forçage du conf VIVANT (celui réellement lu par le service) -- # Le service lit "C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf". # Sur une MISE À JOUR, la propriété MSI NONMSICONFNAME ne réécrit PAS un conf # déjà présent : l'ancienne PSK / identité resterait en place et provoquerait # un échec de handshake TLS (SSL alert 40). On (ré)écrit donc explicitement le # conf ET la clé à cet emplacement pour garantir un trio Hostname / identité / # clé cohérent, quel que soit l'état antérieur du système. $LiveDir = "C:\Program Files\Zabbix Agent 2" $LiveConf = "$LiveDir\zabbix_agent2.conf" $LivePsk = "$LiveDir\zabbix_agent2.psk" Stop-Service -Name "Zabbix Agent 2" -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 1 # Clé PSK au format hex, sans retour à la ligne Set-Content -Path $LivePsk -Value $Enroll.psk -Encoding ASCII -NoNewline if (Test-Path $LiveConf) { Copy-Item $LiveConf "$LiveConf.bak.$(Get-Date -Format yyyyMMddHHmmss)" -ErrorAction SilentlyContinue } # Mode actif uniquement : sans directive Server, Agent 2 desactive les # verifications passives et n'ecoute sur aucun port (rien a ouvrir en entree). @" LogFile=$LiveDir\zabbix_agent2.log ServerActive=$($Enroll.serverActive) Hostname=$($Enroll.hostname) HostMetadata=$($Enroll.hostMetadata) TLSConnect=psk TLSAccept=psk TLSPSKIdentity=$($Enroll.pskIdentity) TLSPSKFile=$LivePsk Include=$LiveDir\zabbix_agent2.d\plugins.d\*.conf "@ | Set-Content -Path $LiveConf -Encoding ASCII # -- Plugin ProcTop (top des processus dans les alertes) -- # Facultatif : en cas d'echec, l'agent fonctionne sans le detail des processus. $PluginUrl = "https://www.logiserv.app/agent-plugin/0.1.0/zabbix-agent2-plugin-proctop-zbx7.4-windows-amd64.exe" $PluginHash = "a58e2246fdebec8b439434beedd08af28a43eedee65ffa556898187da1c0a552" $PluginInstalled = $false if ($PluginUrl) { $PluginDir = "$LiveDir\plugins" $PluginExe = "$PluginDir\zabbix-agent2-plugin-proctop.exe" $PluginTmp = "$env:TEMP\zabbix-agent2-plugin-proctop.exe" try { Invoke-WebRequest -Uri $PluginUrl -OutFile $PluginTmp -UseBasicParsing $PluginGot = (Get-FileHash -Algorithm SHA256 -Path $PluginTmp).Hash.ToLower() if ($PluginGot -ne $PluginHash) { throw "empreinte SHA256 inattendue ($PluginGot)" } New-Item -ItemType Directory -Force -Path $PluginDir | Out-Null Move-Item -Force $PluginTmp $PluginExe New-Item -ItemType Directory -Force -Path "$LiveDir\zabbix_agent2.d\plugins.d" | Out-Null $PluginConf = "$LiveDir\zabbix_agent2.d\plugins.d\proctop.conf" Set-Content -Path $PluginConf -Value @("Plugins.ProcTop.System.Path=$PluginExe", "Plugins.ProcTop.ListenExcludePorts=5353,5355,1900,3702,68,546") -Encoding ASCII Write-Host " OK - Plugin ProcTop installe (detail des processus dans les alertes)." -ForegroundColor Green Write-Host " Binaire : $PluginExe" -ForegroundColor Gray Write-Host " Declaration : $PluginConf" -ForegroundColor Gray Write-Host " Empreinte : SHA256 $PluginHash (verifiee)" -ForegroundColor Gray $PluginInstalled = $true } catch { Remove-Item $PluginTmp -Force -ErrorAction SilentlyContinue Write-Host " Plugin ProcTop non installe ($($_.Exception.Message)) : l'agent fonctionne sans le detail des processus." -ForegroundColor Yellow } } # -- [6/6] Démarrage du service -- Write-Host "" Write-Host "[6/6] Demarrage du service Zabbix Agent 2..." -ForegroundColor Cyan try { Start-Service -Name "Zabbix Agent 2" -ErrorAction SilentlyContinue } catch {} Start-Sleep -Seconds 2 $svc = Get-Service -Name "Zabbix Agent 2" -ErrorAction SilentlyContinue $swTotal.Stop() Write-Host "" Write-Host "===================================================================" -ForegroundColor Green if ($svc -and $svc.Status -eq "Running") { Write-Host " Installation terminee avec succes en $([math]::Round($swTotal.Elapsed.TotalSeconds,0)) s !" -ForegroundColor Green Write-Host " Service Zabbix Agent 2 : demarre (Running)" -ForegroundColor Green } else { Write-Host " Installation terminee en $([math]::Round($swTotal.Elapsed.TotalSeconds,0)) s." -ForegroundColor Yellow Write-Host " Service Zabbix Agent 2 : NON demarre - verifiez le log MSI." -ForegroundColor Yellow } Write-Host "-------------------------------------------------------------------" -ForegroundColor DarkGray Write-Host " Hote : $($Enroll.hostname)" -ForegroundColor Gray Write-Host " Serveur : zabbix.logiserv.re" -ForegroundColor Gray Write-Host " Config : $LiveConf" -ForegroundColor Gray if ($PluginInstalled) { Write-Host " Plugin : $PluginExe" -ForegroundColor Gray } Write-Host " Log MSI : $LogFile" -ForegroundColor Gray Write-Host "===================================================================" -ForegroundColor Green