SSH Client (PowerShell)

From vwiki
Revision as of 09:31, 20 April 2012 by Sstrutt (talk | contribs) (→‎Renci SSH.NET: Some rewording, and added .NET not installed error)
Jump to navigation Jump to search

Tamir Gal SharpSSH

There are a number of examples of using PowerShell to act as a client to interact with SSH servers, all that I've found using Tamir Gal's SharpSSH .NET library - eg PoSh 1010. Its a port of a Java implementation and whilst some people have obviously had success in using it, I always seemed to get the following error when trying to write to SSH session with a Vyatta router...

# ChannelSession.run
System.IO.IOException: Write end dead
  at Tamir.Streams.PipedInputStream.read()
  at Tamir.Streams.PipedInputStream.read(Byte[] b, Int32 off, Int32 len)
  at Tamir.Streams.PipedInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  at Tamir.SharpSsh.java.io.JStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  at Tamir.SharpSsh.jsch.ChannelSession.run()

I suspect the Write end dead fault is caused by the SSH server throwing an error and closing the socket, due to an disliked command. Which in a way, is fair enough, but its not a particularly graceful way of handling things.

Renci SSH.NET

Renci SSH.NET is an ongoing project, its still in beta, but already provides a workable solution with all the core features you're likely to want. Plus as its in active development there's high chance that any probs you might have would be promptly worked on. It provides both .NET 4.0 and 3.5 libraries, you need to use the .NET 3.5 library for PowerShell v2.

To get running you need to download the binary DLL file from http://sshnet.codeplex.com/releases/view/72214, and put it in a place where you can load the assembly into your PowerShell session, eg

[void][reflection.assembly]::LoadFrom( (Resolve-Path ".\lib\RenciSSH\Renci.SshNet.dll") )      # DLL file is in \lib\RenciSSH\ folder below the calling script

If you don't have .NET 3.5 installed, you'll need to do so from https://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21 (the main installer is just a downloader/bootstrapper, there's a full fat install package link at the bottom of the page).

Create a SSH Client object, and connect...

$SshClient = New-Object Renci.SshNet.SshClient("ssh-server", 22, "user", "password")
$SshClient.Connect()

If the connect fails with the following error - you need to install .NET 3.5 (the SSH library is trying to use components that don't exist).

  • Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.

Run a command (eg a Unix ifconfig against the server...

if ($SshClient.IsConnected) {
    $SshCommand = $SshClient.RunCommand("ifconfig")
    $ifconfig = $SshCommand.Result.Split("`n")
}

Clear down...

$SshCommand.Dispose()
$SshClient.Disconnect()
$SshClient.Dispose()