Using SSH to Access Linux Servers in PowerShell

A question I’ve fielded now and again in the past, “Can I use PowerShell to access Linux servers?”. Among others, there were a few answers I could give of varying degrees of usefulness depending on the requirements:

  • Use the command line tool plink.exe
  • Use one of the .NET libraries, sharpSSH or SSH.NET![powershell_linux-300x208]/images/powershell_linux-300x208.png)
  • Look at OMI

I was recently asked this again at my current workplace and discovered a project I hadn’t seen previously, a PowerShell module based on the SSH.NET library.

Once you have downloaded and imported the module, check out what is available:


Get-Command -Module SSH-Sessions

![SSH1]/images/SSH1.png)

To work with a Linux server, first of all you need to establish a session to the server with New-SshSession (I think this cmdlet would benefit from a Credential parameter):


New-SshSession -ComputerName PuppetVM -Username root -Password puppet

![SSH2]/images/SSH2.png)

Examine our connected sessions:


Get-SshSession | Format-Table -AutoSize

![SSH3]/images/SSH3.png)

 

It’s possible to now enter an interactive session with this VM and run some commands, for example to look at the OS and disk space:


Enter-SshSession -ComputerName PuppetVM

cat /proc/version

df -h

exit

![SSH4]/images/SSH4.png)

 

Similar to Invoke-Command in Windows you can use Invoke-SshCommand to send commands to an established session and receive results back (Note: you can use the -Quiet parameter if you don’t wish to see the display on screen):


$Query = Invoke-SshCommand -ComputerName PuppetVM -Command "ls /root"

![SSH5]/images/SSH5.png)

We can now work with these results from the $Query variable. What we get back looks like multiple strings, but is actually an object with a (long) single string


$Query.GetType()

$Query.Count

$Query\[0\].GetType()

![SSH6]/images/SSH6.png)

However, we can work with these a bit easier, should we need to, by breaking them up into individual strings:


$Strings = $Query\[0\] -split "\`n"

$Strings

$Strings.Count

![SSH7a]/images/SSH7a.png)

So far I’ve found this module pretty useful. There are few drawbacks I’ve found so far, including some limitations with ESXi 5.0 and above which are mentioned on the web page, but I hope this project will continue to be updated further.