LLI Wiki — My Digital Knowledge Base

PowerShell : exécuter une commande SSH via un bastion (ProxyJump)

Exécuter une commande sur un serveur Linux derrière un bastion avec OpenSSH -J, ou avec Posh-SSH.

Pour exécuter une commande sur un serveur Linux situé derrière un bastion, il n'est plus recommandé d'utiliser le module Posh-SSH : le client OpenSSH, disponible nativement depuis Windows 10 et Windows Server 2019, gère le rebond avec l'option -J (ProxyJump).

Avec OpenSSH (recommandé)

L'exemple exécute la commande free sur le serveur cible en passant par le bastion, avec une clé privée pour le bastion :

function Connect-ViaProxyJump {
    param(
        [Parameter(Mandatory=$true)]
        [string]$bastionUser,

        [Parameter(Mandatory=$true)]
        [string]$bastionHost,

        [Parameter(Mandatory=$true)]
        [string]$bastionKeyPath,

        [Parameter(Mandatory=$true)]
        [string]$targetUser,

        [Parameter(Mandatory=$true)]
        [string]$targetHost
    )

    # Run 'free' through the jump host and capture the output
    $results = ssh -i $bastionKeyPath -J $bastionUser@$bastionHost -o StrictHostKeyChecking=no -o BatchMode=yes -o PasswordAuthentication=no $targetUser@$targetHost "free"

    if ($results -match "total") {
        Write-Host $results
        return $true
    } else {
        Write-Host "Command failed or no usable output."
        return $false
    }
}

# Usage
$connected = Connect-ViaProxyJump -bastionUser "jumpuser" -bastionHost "bastion01" `
    -bastionKeyPath "C:\keys\bastion_key" -targetUser "appuser" -targetHost "linux01"

if ($connected) { Write-Host "Command executed successfully." }
else { Write-Host "Command failed." }

Avec Posh-SSH (si vous devez le conserver)

On ouvre une session sur le bastion, puis on y lance un second ssh vers la cible :

function Connect-ViaProxyJumpWithPoshSSH {
    param(
        [Parameter(Mandatory=$true)] [string]$bastionUser,
        [Parameter(Mandatory=$true)] [string]$bastionHost,
        [Parameter(Mandatory=$true)] [string]$bastionKeyPath,
        [Parameter(Mandatory=$true)] [string]$targetUser,
        [Parameter(Mandatory=$true)] [string]$targetHost
    )

    $bastionSession = New-SSHSession -HostName $bastionHost -Port 22 -UserName $bastionUser -KeyFile $bastionKeyPath

    $results = Invoke-SSHCommand -SSHSession $bastionSession -Command "ssh $targetUser@$targetHost 'free'"

    Remove-SSHSession -SessionId $bastionSession.SessionId

    if ($results.Output -match "total") {
        Write-Host ($results.Output -join "`n")
        return $true
    } else {
        Write-Host "Command failed or no usable output."
        return $false
    }
}

Remarques

Mastodon LLIMastodon SocialFosstodon