SSH from PowerShell

I’ve been playing with more non Microsoft technologies recently and even have a few Linux VMs running here and there. In the process I’ve learned a lot about interacting between the two worlds/environments using technologies like SSH and even running the Powershell Alpha previews on my Linux VMs. Then I got ‘bored’ and looked for a way to programmatically interact with my VMs (for monitoring) and discovered the open source project SSH.Net which I now have incorporated into even QuickMon. Then I got even more bored and started looking for a way to use SSH from Powershell and came across the SSH-Sessions module which incidentally also use SSH.Net to give Powershell a way to call/connect using SSH.

No PassPhrase

This all works nicely except… SSH-Sessions had one shortcoming.. which I just had to fix. The creator(s) of this module implements a way to specify a key file when connecting to an SSH server but does not provide a way to specify the ‘PassPhrase’ at all! WHY?

Any way, I knew the SSH.Net library does support it since I actually make use of this functionality in QuickMon. Then I started digging inside the SSH-Session script files and made a few adjustments…


To enable PassPhrase functionality I simply had to add the following code in the ‘New-SshSession’ function:

Change the function header to:

function New-SshSession {
    param([Parameter(Mandatory=$true)][string[]] $ComputerName,
          [Parameter(Mandatory=$true)][string]   $Username,
          [string] $KeyFile = '',
          [string] $PassPhrase = 'blankPassphrase',
          [string] $Password = 'SvendsenTechDefault', # I guess allowing for a blank password is "wise"...          
          [int] $Port = 22,
          [switch] $Quiet

and then inside the function:

if ($KeyFile -ne '') {
        if (-not $Quiet) {
            "Key file specified. Will override password. Trying to read key file..."
        if ($PassPhrase -eq 'blankPassphrase') {
            $SecurePassPhrase = Read-Host -AsSecureString "key provided. Please enter pass phrase for $KeyFile"
            $PassPhrase = ConvertFrom-SecureToPlain $SecurePassPhrase
        if (Test-Path -PathType Leaf -Path $Keyfile) {
            $Key = New-Object Renci.SshNet.PrivateKeyFile( $Keyfile, $PassPhrase ) -ErrorAction Stop
        else {
            "Specified keyfile does not exist: '$KeyFile'."


And with the you can now use the module to connect to SSH using a Key file that has a PassPhrase. If you don’t specify the PassPhrase the script will prompt you for one. If you actually don’t have a PassPhrase at all then pass an empty string as the value of PassPhrase (not tested but it should work).

Import-Module SSH-Sessions
New-SshSession -Computer mySSHServer -Username me  -KeyFile 'c:\mykeys\mykey.key' -PassPhrase 'somePhrase'
Invoke-SshCommand  -ComputerName mySSHServer -Command "cat /proc/cpuinfo | grep processor" -Quiet
Remove-SshSession -RemoveAll -Quiet

Leave a Reply

%d bloggers like this: