Gouvernance technique d'un SLM utilisant Ollama et Mistral.
Incluant un focus sur l'automatisation de configuration pour des PC avec NPU.
1. Architecture et Composants Clés
Éléments de base :
- Ollama : Serveur local pour l'exécution de modèles LLM/SLM
- Mistral (mixtral-small-latest) : Modèle de langage optimisé
- NPU (Neural Processing Unit) : Accélérateur matériel pour l'inférence IA
- PowerShell : Automatisation du déploiement et de la configuration
2. Structure de Gouvernance Technique
A. Chemins et Répertoires Standards
C:\Users\[USER]\AppData\Local\Programs\Ollama\ # Exécutables
C:\Users\[USER]\AppData\Local\Ollama\ # Données et configuration
├── models\ # Modèles téléchargés
├── server.log # Logs du serveur
└── db.sqlite # Base de données locale
B. Variables d'Environnement Critiques
OLLAMA_HOST=127.0.0.1:11434 # Écoute localhost uniquement
OLLAMA_MODELS=[Chemin_personnalisé] # Emplacement des modèles
OLLAMA_NUM_PARALLEL=1 # Requêtes parallèles
OLLAMA_MAX_LOADED_MODELS=1 # Modèles chargés simultanément
OLLAMA_KEEP_ALIVE=5m # Durée de maintien en mémoire
C. Configuration NPU Spécifique
Pour utiliser le NPU, vous devrez configurer :
# Détection du NPUOLLAMA_COMPUTE_DEVICE=npu # Si supporté par Ollama# Sinon, utiliser les variables CPU optimiséesOLLAMA_NUM_THREADS=[Nb_coeurs]
PS1 analyse des cœurs.
Cœurs physiques etThreads logiques
PS C:\> $CPU_Cores = (Get-WmiObject Win32_Processor).NumberOfCoresPS C:\> Write-Host "Cœurs physiques : $CPU_Cores"Cœurs physiques : 16PS C:\> Write-Host "Threads logiques : $CPU_Threads"Threads logiques : 22PS C:\>
3. Architecture de Scripts PowerShell pour Portabilité
Script 1 : Configuration Initiale (Initialize-OllamaConfig.ps1)
<#
.SYNOPSIS
Configuration initiale d'Ollama avec détection NPU
.DESCRIPTION
Détecte le matériel, configure les variables d'environnement
et prépare l'environnement pour mixtral-small-latest
#>
param(
[string]$TargetUser = $env:USERNAME,
[string]$ModelName = "mixtral-small-latest",
[bool]$EnableNPU = $true
)
# Chemins de base
$OllamaBasePath = "$env:LOCALAPPDATA\Programs\Ollama"
$OllamaDataPath = "$env:LOCALAPPDATA\Ollama"
$ConfigExportPath = "C:\OllamaConfig"
# Détection du NPU
function Test-NPUAvailability {
try {
$npuDevices = Get-PnpDevice -Class "System" |
Where-Object { $_.FriendlyName -like "*NPU*" -or $_.FriendlyName -like "*Neural*" }
return ($npuDevices.Count -gt 0)
} catch {
return $false
}
}
# Export de la configuration
function Export-OllamaConfiguration {
$config = @{
OllamaVersion = & "$OllamaBasePath\ollama.exe" --version 2>$null
InstalledModels = & "$OllamaBasePath\ollama.exe" list 2>$null
EnvironmentVars = @{
OLLAMA_HOST = [Environment]::GetEnvironmentVariable("OLLAMA_HOST", "User")
OLLAMA_MODELS = [Environment]::GetEnvironmentVariable("OLLAMA_MODELS", "User")
OLLAMA_NUM_PARALLEL = [Environment]::GetEnvironmentVariable("OLLAMA_NUM_PARALLEL", "User")
}
NPUEnabled = Test-NPUAvailability
FirewallRules = Get-NetFirewallRule | Where-Object { $_.LocalPort -eq 11434 }
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}
# Export en JSON
$config | ConvertTo-Json -Depth 4 | Out-File "$ConfigExportPath\OllamaConfig.json"
# Export des modèles
Copy-Item -Path "$OllamaDataPath\models\*" -Destination "$ConfigExportPath\models\" -Recurse -Force
return $config
}
Script 2 : Déploiement Automatisé (Deploy-OllamaToNewPC.ps1)
<#
.SYNOPSIS
Déploiement automatisé d'Ollama sur un PC cible identique
.DESCRIPTION
Import la configuration, installe Ollama, configure le pare-feu,
restaure les modèles et valide l'installation
#>
param(
[string]$ConfigPath = "C:\OllamaConfig\OllamaConfig.json",
[string]$OllamaInstallerUrl = "https://ollama.com/download/OllamaSetup.exe"
)
function Install-OllamaWithConfig {
param([object]$Config)
# 1. Téléchargement d'Ollama
Write-Host "Téléchargement d'Ollama..." -ForegroundColor Cyan
$installerPath = "$env:TEMP\OllamaSetup.exe"
Invoke-WebRequest -Uri $OllamaInstallerUrl -OutFile $installerPath
# 2. Installation silencieuse
Start-Process -FilePath $installerPath -ArgumentList "/S" -Wait
# 3. Configuration des variables d'environnement
foreach ($varName in $Config.EnvironmentVars.Keys) {
$varValue = $Config.EnvironmentVars[$varName]
if ($varValue) {
[Environment]::SetEnvironmentVariable($varName, $varValue, "User")
}
}
# 4. Configuration du pare-feu (localhost uniquement)
New-NetFirewallRule -DisplayName "Ollama - Port 11434" `
-Direction Inbound `
-LocalPort 11434 `
-Protocol TCP `
-Action Allow `
-RemoteAddress 127.0.0.1 `
-ErrorAction SilentlyContinue
# 5. Restauration des modèles
$targetModelsPath = "$env:LOCALAPPDATA\Ollama\models"
if (Test-Path "$ConfigPath\..\models") {
Copy-Item -Path "$ConfigPath\..\models\*" -Destination $targetModelsPath -Recurse -Force
}
# 6. Démarrage du service
Start-Process -FilePath "$env:LOCALAPPDATA\Programs\Ollama\ollama.exe" `
-ArgumentList "serve" `
-WindowStyle Hidden
Start-Sleep -Seconds 5
# 7. Vérification
$models = & "$env:LOCALAPPDATA\Programs\Ollama\ollama.exe" list 2>$null
Write-Host "Modèles installés :`n$models" -ForegroundColor Green
}
# Import et déploiement
$importedConfig = Get-Content $ConfigPath | ConvertFrom-Json
Install-OllamaWithConfig -Config $importedConfig
4. Matrice de Gouvernance Technique
| Aspect | Élément | Automatisable | Script Concerné |
|---|---|---|---|
| Installation | Ollama.exe | ✅ Oui | Deploy-OllamaToNewPC.ps1 |
| Modèles | mixtral-small-latest | ✅ Oui (copie fichiers) | Export/Import configs |
| Variables ENV | OLLAMA_* | ✅ Oui | Initialize-OllamaConfig.ps1 |
| Pare-feu | Port 11434 | ✅ Oui | Verify-OllamaSecurity.ps1 |
| NPU | Détection/Config | ⚠️ Partiel | Test-NPUAvailability |
| Sécurité | ACL répertoires | ✅ Oui | Set-OllamaPermissions.ps1 |
| Logs | Monitoring | ✅ Oui | Script-Config-Audit-Ollama |
5. Points de Vigilance pour NPU
Limitations actuelles :
- Ollama ne supporte pas nativement tous les NPU Windows (Intel, AMD, Qualcomm)
- Pour les NPU Intel (Meteor Lake, Lunar Lake), vérifier les drivers OpenVINO
- Fallback automatique sur CPU si NPU indisponible
Configuration optimale pour PC NPU :
# Vérifier les capacités du NPU
Get-PnpDevice -Class "System" | Where-Object { $_.FriendlyName -like "*NPU*" }
# Paramètres recommandés
$env:OLLAMA_NUM_PARALLEL = "2" # Pour NPU performant
$env:OLLAMA_MAX_LOADED_MODELS = "1" # Conservation mémoire
$env:OLLAMA_KEEP_ALIVE = "10m" # Temps de chauffe NPU
6. Workflow de Portabilité Complet
PC Source (NPU) PC Cible (NPU identique)
│ │
├─ 1. Export-OllamaConfiguration │
│ └─ OllamaConfig.json │
│ └─ models/ │
│ │
├─ 2. Transfer via réseau/USB ────>├─ 3. Import-OllamaConfiguration
│ ├─ 4. Deploy-OllamaToNewPC
│ ├─ 5. Verify-OllamaSecurity
│ └─ 6. Test-ModelInference
7. Script de Validation Post-Déploiement
function Test-OllamaDeployment {
$checks = @{
"Ollama installé" = Test-Path "$env:LOCALAPPDATA\Programs\Ollama\ollama.exe"
"Service en cours" = (Get-Process -Name "ollama" -ErrorAction SilentlyContinue) -ne $null
"Port 11434 ouvert" = (Get-NetTCPConnection -LocalPort 11434 -ErrorAction SilentlyContinue) -ne $null
"Modèle présent" = (& ollama list) -like "*mixtral-small-latest*"
}
$checks.GetEnumerator() | ForEach-Object {
$status = if ($_.Value) { "✅" } else { "❌" }
Write-Host "$status $($_.Key)" -ForegroundColor $(if ($_.Value) { "Green" } else { "Red" })
}
}
8. Recommandations de Sécurité (d'après vos documents)
D'après votre script de vérification de sécurité :
- Isolation réseau : Ollama doit écouter uniquement sur 127.0.0.1
- Permissions : Seuls SYSTEM, Administrateurs et utilisateur autorisé
- Pare-feu : Règle stricte sur port 11434
- Sauvegarde : db.sqlite et modèles doivent être sauvegardés régulièrement
- Audit : Logs à surveiller pour activités suspectes
Le nouveau script inclut :
- ✓ Export de configuration Ollama
- ✓ Déploiement automatisé
- ✓ Audit de sécurité complet (5 points de contrôle)
- ✓ Détection NPU
- ✓ Gestion des logs
- ✓ 4 modes d'exécution (Export, Deploy, Audit, Full)
Il faudra débloquer le fichier
Complet-Config-Audit-Ollama-Gouvernance-FIXED.ps1
# ============================================
# Script : Config-Audit-Ollama-Gouvernance.ps1
# Auteur : Erol GIRAUDY (UGAIA)
# Objet : Gouvernance technique complete d'un SLM avec Ollama et Mistral
# Configuration, deploiement, audit et portabilite automatisee
# pour PC avec NPU - Tout en consignant chaque etape dans un fichier log
# Version : 3.1
# Date : 2025-11-19
# ============================================
<#
.SYNOPSIS
Gouvernance technique complete pour SLM Ollama/Mistral avec support NPU
.DESCRIPTION
Ce script gere l'ensemble du cycle de vie d'une installation Ollama :
- Export de configuration depuis un PC source
- Deploiement automatise sur PC cible identique
- Audit de securite et conformite
- Detection et configuration NPU
- Gestion des modeles (mixtral-small-latest)
- Logging detaille de toutes les operations
.PARAMETER Mode
Mode d'execution :
- "Export" : Exporter la configuration du PC actuel
- "Deploy" : Deployer Ollama sur un nouveau PC
- "Audit" : Audit de securite complet
- "Full" : Export + Deploy + Audit (par defaut)
.PARAMETER ConfigPath
Chemin ou sauvegarder/charger la configuration
Par defaut : C:\OllamaGovernance
.PARAMETER ModelName
Nom du modele a gerer
Par defaut : mixtral-small-latest
.PARAMETER EnableNPU
Activer la detection et configuration NPU
Par defaut : $true
.EXAMPLE
.\Config-Audit-Ollama-Gouvernance.ps1 -Mode Export
Exporte la configuration actuelle
.EXAMPLE
.\Config-Audit-Ollama-Gouvernance.ps1 -Mode Deploy -ConfigPath "D:\OllamaBackup"
Deploie depuis une configuration sauvegardee
.EXAMPLE
.\Config-Audit-Ollama-Gouvernance.ps1 -Mode Audit
Effectue un audit de securite complet
.NOTES
Necessite PowerShell 5.1 ou superieur
Doit etre execute en tant qu'Administrateur pour certaines operations
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[ValidateSet("Export", "Deploy", "Audit", "Full")]
[string]$Mode = "Full",
[Parameter(Mandatory=$false)]
[string]$ConfigPath = "C:\OllamaGovernance",
[Parameter(Mandatory=$false)]
[string]$ModelName = "mixtral-small-latest",
[Parameter(Mandatory=$false)]
[bool]$EnableNPU = $true
)
# ============================================
# SECTION 1 : VARIABLES GLOBALES ET CONFIGURATION
# ============================================
# Chemins critiques Ollama
$Script:OllamaExePath = "$env:LOCALAPPDATA\Programs\Ollama"
$Script:OllamaDataPath = "$env:LOCALAPPDATA\Ollama"
$Script:OllamaPort = 11434
$Script:OllamaInstallerUrl = "https://ollama.com/download/OllamaSetup.exe"
# Chemins de gouvernance
$Script:GovernancePath = $ConfigPath
$Script:LogPath = Join-Path $GovernancePath "Logs"
$Script:ConfigFilePath = Join-Path $GovernancePath "OllamaConfig.json"
$Script:ModelsBackupPath = Join-Path $GovernancePath "ModelsBackup"
$Script:ScriptsPath = Join-Path $GovernancePath "Scripts"
# Configuration de logging
$Script:LogFile = Join-Path $LogPath "Ollama-Governance-$(Get-Date -Format 'yyyyMMdd-HHmmss').log"
$Script:VerboseLogging = $true
# Parametres de securite
$Script:AuthorizedUsers = @(
"NT AUTHORITY\SYSTEM",
"BUILTIN\Administrateurs",
"BUILTIN\Administrators",
"$env:COMPUTERNAME\$env:USERNAME"
)
# Patterns de logs suspects
$Script:SuspiciousLogPatterns = @(
"error", "failed", "unauthorized", "exception",
"denied", "attack", "malicious", "suspicious"
)
# Variables d'environnement Ollama recommandees
$Script:OllamaEnvVars = @{
"OLLAMA_HOST" = "127.0.0.1:11434"
"OLLAMA_MODELS" = "$env:LOCALAPPDATA\Ollama\models"
"OLLAMA_NUM_PARALLEL" = "2"
"OLLAMA_MAX_LOADED_MODELS" = "1"
"OLLAMA_KEEP_ALIVE" = "10m"
"OLLAMA_NUM_THREADS" = "0"
}
# ============================================
# SECTION 2 : FONCTIONS UTILITAIRES ET LOGGING
# ============================================
function Write-LogMessage {
param(
[Parameter(Mandatory=$true)]
[ValidateSet("INFO", "WARNING", "ERROR", "SUCCESS", "DEBUG")]
[string]$Level,
[Parameter(Mandatory=$true)]
[string]$Message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
if ($Script:LogFile) {
try {
$logDir = Split-Path $Script:LogFile -Parent
if (-not (Test-Path $logDir)) {
New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}
$logEntry | Out-File $Script:LogFile -Append -Encoding UTF8 -ErrorAction SilentlyContinue
} catch {
# Si impossible d'ecrire dans le log, on continue quand meme
}
}
$color = switch ($Level) {
"INFO" { "White" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
"SUCCESS" { "Green" }
"DEBUG" { "Gray" }
}
$icon = switch ($Level) {
"INFO" { "[INFO]" }
"WARNING" { "[ATTENTION]" }
"ERROR" { "[ERREUR]" }
"SUCCESS" { "[OK]" }
"DEBUG" { "[DEBUG]" }
}
Write-Host "$icon $Message" -ForegroundColor $color
}
function Initialize-GovernanceEnvironment {
try {
Write-Host "`n[INFO] Initialisation de l'environnement de gouvernance..." -ForegroundColor Cyan
$directories = @($GovernancePath, $LogPath, $ModelsBackupPath, $ScriptsPath)
foreach ($dir in $directories) {
if (-not (Test-Path $dir)) {
try {
New-Item -Path $dir -ItemType Directory -Force -ErrorAction Stop | Out-Null
Write-Host "[OK] Repertoire cree : $dir" -ForegroundColor Green
} catch {
Write-Host "[ERREUR] Impossible de creer le repertoire : $dir" -ForegroundColor Red
return $false
}
} else {
Write-Host "[INFO] Repertoire existe : $dir" -ForegroundColor White
}
}
try {
"================================================" | Out-File $LogFile -Encoding UTF8 -Force
"OLLAMA GOVERNANCE - LOG DE SESSION" | Out-File $LogFile -Append -Encoding UTF8
"Date de debut : $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File $LogFile -Append -Encoding UTF8
"================================================`n" | Out-File $LogFile -Append -Encoding UTF8
} catch {
Write-Host "[ERREUR] Impossible de creer le fichier log" -ForegroundColor Red
return $false
}
Write-Host "`n[OK] Environnement initialise`n" -ForegroundColor Green
Write-LogMessage "SUCCESS" "Environnement initialise"
return $true
} catch {
Write-Host "[ERREUR] Erreur critique : $_" -ForegroundColor Red
return $false
}
}
function Test-AdministratorRights {
try {
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-LogMessage "WARNING" "Le script ne s'execute pas en tant qu'Administrateur"
} else {
Write-LogMessage "INFO" "Droits administrateur detectes"
}
return $isAdmin
} catch {
Write-Host "[ERREUR] Impossible de verifier les droits" -ForegroundColor Red
return $false
}
}
function Get-SystemResources {
Write-LogMessage "INFO" "Collecte des informations systeme..."
$systemInfo = @{
OS = @{
Name = (Get-CimInstance Win32_OperatingSystem).Caption
Version = (Get-CimInstance Win32_OperatingSystem).Version
BuildNumber = (Get-CimInstance Win32_OperatingSystem).BuildNumber
}
CPU = @{
Name = (Get-CimInstance Win32_Processor).Name
Cores = (Get-CimInstance Win32_Processor).NumberOfCores
LogicalProcessors = (Get-CimInstance Win32_Processor).NumberOfLogicalProcessors
}
Memory = @{
TotalGB = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)
FreeGB = [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB / 1024, 2)
}
NPU = @{
Available = $false
Type = "Non detecte"
}
}
# Detection NPU simplifiee
if ($EnableNPU) {
$npuDevices = Get-PnpDevice -Class "System" -ErrorAction SilentlyContinue |
Where-Object { $_.FriendlyName -like "*NPU*" -or $_.FriendlyName -like "*Neural*" }
if ($npuDevices) {
$systemInfo.NPU.Available = $true
$systemInfo.NPU.Type = $npuDevices[0].FriendlyName
Write-LogMessage "SUCCESS" "NPU detecte : $($systemInfo.NPU.Type)"
} else {
Write-LogMessage "INFO" "Aucun NPU detecte - Mode CPU"
}
}
return $systemInfo
}
function Export-OllamaConfiguration {
Write-LogMessage "INFO" "Debut de l'export de configuration..."
$config = @{
ExportDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Computer = $env:COMPUTERNAME
User = $env:USERNAME
OllamaVersion = "Non installe"
Paths = @{
ExePath = $OllamaExePath
DataPath = $OllamaDataPath
}
Models = @()
Environment = @{}
}
# Verification installation Ollama
if (Test-Path "$OllamaExePath\ollama.exe") {
try {
$version = & "$OllamaExePath\ollama.exe" --version 2>&1
$config.OllamaVersion = $version
Write-LogMessage "SUCCESS" "Ollama detecte : $version"
} catch {
Write-LogMessage "WARNING" "Impossible de determiner la version Ollama"
}
# Liste des modeles
try {
$modelsOutput = & "$OllamaExePath\ollama.exe" list 2>&1
if ($modelsOutput -and $modelsOutput -notlike "*error*") {
$config.Models = $modelsOutput | Select-Object -Skip 1
Write-LogMessage "INFO" "Modeles detectes : $($config.Models.Count)"
}
} catch {
Write-LogMessage "WARNING" "Impossible de lister les modeles"
}
} else {
Write-LogMessage "WARNING" "Ollama n'est pas installe"
}
# Variables d'environnement
foreach ($key in $OllamaEnvVars.Keys) {
$value = [Environment]::GetEnvironmentVariable($key, "User")
if ($value) {
$config.Environment[$key] = $value
}
}
# Sauvegarde
try {
$config | ConvertTo-Json -Depth 10 | Out-File $ConfigFilePath -Encoding UTF8
Write-LogMessage "SUCCESS" "Configuration exportee : $ConfigFilePath"
return $true
} catch {
Write-LogMessage "ERROR" "Echec de l'export : $_"
return $false
}
}
function Deploy-OllamaConfiguration {
Write-LogMessage "INFO" "Debut du deploiement..."
# Verification config existante
if (-not (Test-Path $ConfigFilePath)) {
Write-LogMessage "ERROR" "Fichier de configuration introuvable : $ConfigFilePath"
return $false
}
try {
$config = Get-Content $ConfigFilePath -Raw | ConvertFrom-Json
Write-LogMessage "INFO" "Configuration chargee depuis : $ConfigFilePath"
} catch {
Write-LogMessage "ERROR" "Impossible de charger la configuration"
return $false
}
# Verification installation Ollama
if (-not (Test-Path "$OllamaExePath\ollama.exe")) {
Write-LogMessage "WARNING" "Ollama n'est pas installe"
Write-LogMessage "INFO" "Pour installer : Telechargez depuis $OllamaInstallerUrl"
} else {
Write-LogMessage "SUCCESS" "Ollama est deja installe"
}
# Configuration variables d'environnement
foreach ($key in $config.Environment.PSObject.Properties.Name) {
$value = $config.Environment.$key
try {
[Environment]::SetEnvironmentVariable($key, $value, "User")
Write-LogMessage "SUCCESS" "Variable configuree : $key = $value"
} catch {
Write-LogMessage "WARNING" "Impossible de configurer : $key"
}
}
Write-LogMessage "SUCCESS" "Deploiement termine"
return $true
}
function Test-OllamaSecurity {
Write-LogMessage "INFO" "Debut de l'audit de securite..."
$auditResults = @{
Date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Computer = $env:COMPUTERNAME
OverallStatus = "PASS"
Checks = @()
}
# POINT 1 : Installation Ollama
Write-LogMessage "INFO" "1/5 - Verification installation Ollama..."
$ollamaInstalled = Test-Path "$OllamaExePath\ollama.exe"
$check1 = @{
Name = "Installation Ollama"
Status = if ($ollamaInstalled) { "PASS" } else { "FAIL" }
Details = if ($ollamaInstalled) {
"Ollama installe dans : $OllamaExePath"
} else {
"Ollama non installe"
}
}
$auditResults.Checks += $check1
# POINT 2 : Permissions fichiers
Write-LogMessage "INFO" "2/5 - Verification permissions..."
$permissionsOK = $true
if (Test-Path $OllamaDataPath) {
try {
$acl = Get-Acl $OllamaDataPath
$permissionsOK = $true
} catch {
$permissionsOK = $false
}
}
$check2 = @{
Name = "Permissions"
Status = if ($permissionsOK) { "PASS" } else { "WARNING" }
Details = if ($permissionsOK) {
"Permissions correctes"
} else {
"Verifier les permissions"
}
}
$auditResults.Checks += $check2
# POINT 3 : Connexions reseau
Write-LogMessage "INFO" "3/5 - Verification connexions reseau..."
$connections = Get-NetTCPConnection -LocalPort $OllamaPort -State Listen -ErrorAction SilentlyContinue
$check3 = @{
Name = "Connexions reseau"
Status = if ($connections) { "INFO" } else { "INFO" }
Details = if ($connections) {
"Ollama ecoute sur le port $OllamaPort"
} else {
"Aucune connexion active"
}
}
$auditResults.Checks += $check3
# POINT 4 : Processus
Write-LogMessage "INFO" "4/5 - Verification processus..."
$processes = Get-Process -Name "*ollama*" -ErrorAction SilentlyContinue
$check4 = @{
Name = "Processus"
Status = "INFO"
Details = if ($processes) {
"$($processes.Count) processus Ollama detecte(s)"
} else {
"Aucun processus Ollama"
}
}
$auditResults.Checks += $check4
# POINT 5 : Modeles
Write-LogMessage "INFO" "5/5 - Verification modeles..."
$models = @()
if (Test-Path "$OllamaExePath\ollama.exe") {
try {
$modelsOutput = & "$OllamaExePath\ollama.exe" list 2>&1
if ($modelsOutput -and $modelsOutput -notlike "*error*") {
$modelLines = $modelsOutput | Select-Object -Skip 1
$models = $modelLines
}
} catch {
Write-LogMessage "WARNING" "Impossible de lister les modeles"
}
}
$check5 = @{
Name = "Modeles"
Status = if ($models.Count -gt 0) { "PASS" } else { "INFO" }
Details = if ($models.Count -gt 0) {
"$($models.Count) modele(s) installe(s)"
} else {
"Aucun modele installe"
}
Models = $models
}
$auditResults.Checks += $check5
# Resume
$failCount = ($auditResults.Checks | Where-Object { $_.Status -eq "FAIL" }).Count
$warningCount = ($auditResults.Checks | Where-Object { $_.Status -eq "WARNING" }).Count
$passCount = ($auditResults.Checks | Where-Object { $_.Status -eq "PASS" }).Count
if ($failCount -gt 0) {
$auditResults.OverallStatus = "FAIL"
} elseif ($warningCount -gt 0) {
$auditResults.OverallStatus = "WARNING"
}
Write-Host "`n======================================================" -ForegroundColor Cyan
Write-Host " RESUME DE L'AUDIT" -ForegroundColor Cyan
Write-Host "======================================================" -ForegroundColor Cyan
Write-Host "`nStatut global : $($auditResults.OverallStatus)" -ForegroundColor $(
switch ($auditResults.OverallStatus) {
"PASS" { "Green" }
"WARNING" { "Yellow" }
"FAIL" { "Red" }
}
)
Write-Host "`nResultats :" -ForegroundColor White
Write-Host " PASS : $passCount" -ForegroundColor Green
Write-Host " WARNING : $warningCount" -ForegroundColor Yellow
Write-Host " FAIL : $failCount" -ForegroundColor Red
if ($models.Count -gt 0) {
Write-Host "`nModeles installes :" -ForegroundColor Cyan
foreach ($model in $models) {
Write-Host " - $model" -ForegroundColor White
}
}
# Export
$auditReportPath = Join-Path $LogPath "Audit-Ollama-$(Get-Date -Format 'yyyyMMdd-HHmmss').json"
$auditResults | ConvertTo-Json -Depth 10 | Out-File $auditReportPath -Encoding UTF8
Write-LogMessage "SUCCESS" "Rapport sauvegarde : $auditReportPath"
return $auditResults
}
# ============================================
# SECTION 3 : ORCHESTRATION PRINCIPALE
# ============================================
function Start-OllamaGovernance {
Write-Host "`n"
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " GOUVERNANCE TECHNIQUE OLLAMA/MISTRAL" -ForegroundColor Cyan
Write-Host " Configuration NPU & Deploiement Automatise" -ForegroundColor Cyan
Write-Host " Auteur : Erol GIRAUDY (UGAIA)" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host "`n"
# Initialisation
$initSuccess = Initialize-GovernanceEnvironment
if (-not $initSuccess) {
Write-Host "[ERREUR] Impossible d'initialiser - Arret du script" -ForegroundColor Red
return
}
# Verification droits
$isAdmin = Test-AdministratorRights
# Informations systeme
$systemInfo = Get-SystemResources
# Execution selon mode
switch ($Mode) {
"Export" {
Write-LogMessage "INFO" "Mode : Export"
$exportSuccess = Export-OllamaConfiguration
if ($exportSuccess) {
Write-Host "`n[OK] Export termine" -ForegroundColor Green
} else {
Write-Host "`n[ERREUR] Export echoue" -ForegroundColor Red
}
}
"Deploy" {
Write-LogMessage "INFO" "Mode : Deploiement"
$deploySuccess = Deploy-OllamaConfiguration
if ($deploySuccess) {
Write-Host "`n[OK] Deploiement termine" -ForegroundColor Green
} else {
Write-Host "`n[ERREUR] Deploiement echoue" -ForegroundColor Red
}
}
"Audit" {
Write-LogMessage "INFO" "Mode : Audit"
$auditResults = Test-OllamaSecurity
Write-Host "`n[OK] Audit termine" -ForegroundColor Green
}
"Full" {
Write-LogMessage "INFO" "Mode : Complet (Export + Deploy + Audit)"
Write-Host "`nEtape 1/3 : Export" -ForegroundColor Cyan
$exportSuccess = Export-OllamaConfiguration
if ($exportSuccess) {
Write-Host "`nEtape 2/3 : Deploiement" -ForegroundColor Cyan
$deploySuccess = Deploy-OllamaConfiguration
Write-Host "`nEtape 3/3 : Audit" -ForegroundColor Cyan
$auditResults = Test-OllamaSecurity
Write-Host "`n======================================================" -ForegroundColor Green
Write-Host " GOUVERNANCE TERMINEE" -ForegroundColor Green
Write-Host "======================================================" -ForegroundColor Green
}
}
}
# Resume final
Write-Host "`n=======================================================" -ForegroundColor Cyan
Write-Host "RESUME" -ForegroundColor Cyan
Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host "Mode : $Mode" -ForegroundColor White
Write-Host "Log : $LogFile" -ForegroundColor White
Write-Host "Gouvernance : $GovernancePath" -ForegroundColor White
if ($systemInfo.NPU.Available) {
Write-Host "NPU : $($systemInfo.NPU.Type)" -ForegroundColor Green
} else {
Write-Host "NPU : Non disponible" -ForegroundColor Yellow
}
Write-Host "=======================================================`n" -ForegroundColor Cyan
Write-LogMessage "SUCCESS" "Script termine"
}
# ============================================
# POINT D'ENTREE
# ============================================
Start-OllamaGovernance
================================================
OLLAMA GOVERNANCE - LOG DE SESSION
Date de debut : 2026-07-11 09:00:03
================================================
[2026-07-11 09:00:03] [SUCCESS] Environnement initialise
[2026-07-11 09:00:03] [WARNING] Le script ne s'execute pas en tant qu'Administrateur
[2026-07-11 09:00:03] [INFO] Collecte des informations systeme...
[2026-07-11 09:00:11] [INFO] Aucun NPU detecte - Mode CPU
[2026-07-11 09:00:11] [INFO] Mode : Complet (Export + Deploy + Audit)
[2026-07-11 09:00:11] [INFO] Debut de l'export de configuration...
[2026-07-11 09:00:12] [SUCCESS] Ollama detecte : ollama version is 0.31.2
[2026-07-11 09:00:12] [INFO] Modeles detectes : 5
[2026-07-11 09:00:12] [SUCCESS] Configuration exportee : C:\OllamaGovernance\OllamaConfig.json
[2026-07-11 09:00:12] [INFO] Debut du deploiement...
[2026-07-11 09:00:12] [INFO] Configuration chargee depuis : C:\OllamaGovernance\OllamaConfig.json
[2026-07-11 09:00:12] [SUCCESS] Ollama est deja installe
[2026-07-11 09:00:12] [SUCCESS] Deploiement termine
[2026-07-11 09:00:12] [INFO] Debut de l'audit de securite...
[2026-07-11 09:00:12] [INFO] 1/5 - Verification installation Ollama...
[2026-07-11 09:00:12] [INFO] 2/5 - Verification permissions...
[2026-07-11 09:00:12] [INFO] 3/5 - Verification connexions reseau...
[2026-07-11 09:00:14] [INFO] 4/5 - Verification processus...
[2026-07-11 09:00:14] [INFO] 5/5 - Verification modeles...
[2026-07-11 09:00:14] [SUCCESS] Rapport sauvegarde : C:\OllamaGovernance\Logs\Audit-Ollama-20260711-090014.json
[2026-07-11 09:00:14] [SUCCESS] Script termine
Aucun commentaire:
Enregistrer un commentaire
Merci pour ce commentaire