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
- Download PuTTY von http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
- PuTTY.exe - SSH Client
- PSCP.exe - SCP Client
- plink.exe - commandline Interface für Putty / SSH / SCP
- puttygen.exe - commandline Interface für Putty / SSH / SCP
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
- Man startet die Session Interaktiv und gibt jeweils das Passwort ein
- Nachteil: Nervt auf Dauer, schlecht für Automatisierung, keine Rückgabewerte der Funktionen
- aber einfach
Passwort as Parameter
- Man übergibt das Passwort als Parameter
- Nachteil: Passwort steht irgendwo im Klartext
RSA Keys
- Man definiert ein Private/Public Key und logged sich darüber ein
- Dafür muss man ein Keypair erzeugen (puttygen) und auf dem Zielserver den erzeugten PUB-Key in die /home/user/.ssh/authorized_keys einfügen
- Besser als Passwort as Parameter, aber Private Key steht irgendwo und ändert sich nicht
GSSAPI / SPNEGO
- Login am Linux Rechner mit Windows Credentials per NTLMv2 / Kerberos Negotiation
- Muss zunächst am Linux Rechner konfiguriert werden (AD Anbindung usw.)
- Aufwändig zu konfigurieren, auf Dauer beste Lösung
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 ...