Run SSH command from Powershell with PuTTy plink

Powershell unterstützt nativ keine SSH Sessions. Es gibt zwar externe Module, die man einbinden kann - einige sind aber Lizenzpflichtig - andere nicht unbedingt vertrauenserweckend. Als Workaround kann man einfach die Commandline von PuTTY verwenden, um eine SSH Session aus der Powershell zu öffnen und einen Befehl abzusetzen.


Wer als Admin seine Scripte zwischen Linux und Windows Welt konsolidieren möchte kann per Powershell auch Befehle über SSH ausführen ...

Contents

Installation

Authentifizierung

Um sich aus der Powershell auf dem Linux Rechner zu authentifizieren gibt es mehrere Möglichkeiten ... natürlich alle mit Vor- und Nachteilen.

Passwort from Keyboard

Passwort as Parameter

RSA Keys

GSSAPI / SPNEGO

Beispiel Script

##################################################
#
# author / copyright              Nov 09 slash4.de
#
##################################################
 
function run-SSH( 
		[string] $linuxHostname,
		[string] $linuxCommand ) 
{
	$plink = "\\your\path\to\PuTTy\plink.exe"
 
        # takes windows logon username
	$myWinUsername = gc Env:\USERNAME
 
        # use RSA keyfile for authentication
	$myConStr = $plink + " -i `"$HOME\ssh\putty.ppk`" " + $myWinUsername +"@"+ $linuxHostname + " `"" + $linuxCommand + "`""
 
        # uncomment for simple password auth - type password even without prompt
        # $myConStr = $plink + " " + $myWinUsername +"@"+ $linuxHostname + " `"" + $linuxCommand + "`""
 
        return Invoke-Expression $myConStr
}

Test run / error handling

#====== test run =============
 
#test 1
if ($res = run-SSH myhostname.slash4.de "ls -altr") 
{ 
 "command ran successfully"
 "output was: "
 $res
} 
else 
{ "command had an error" }
 
 
#test 2 - force an error
if ($res = run-SSH myhostname.slash4.de "lulu") 
{ 
 "command ran successfully"
 "output was: "
 $res
} 
else 
{ "command had an error" }

I will update this soon with an SCP function and SPNEGO auth howto ...