PowerShell: run an SSH command through a bastion (ProxyJump)
Run a command on a Linux server behind a bastion with OpenSSH -J, or with Posh-SSH.
To run a command on a Linux server located behind a bastion, using the Posh-SSH module is no longer recommended: the OpenSSH client, built into Windows 10 and Windows Server 2019 and later, handles the hop with the -J option (ProxyJump).
With OpenSSH (recommended)
The example runs the free command on the target server through the bastion, using a private key for the 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." }
With Posh-SSH (if you must keep it)
Open a session on the bastion, then run a second ssh from there to the target:
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
}
}
Notes
StrictHostKeyChecking=nodisables host key verification: avoid it outside a test environment.- With
BatchMode=yesandPasswordAuthentication=no, the connection to the target must work with a key, without any password prompt.