Tuesday, January 31, 2012

Running SSH commands from Powershell

There is a really simple way of running ssh commands on unix/linux boxes from a Powershell script. In fact, altough Powershell does not natively support running ssh commands, it can rely on external third party tools to get the job done. The tool I am talking about today is Plink.

Plink (Putty link) is a Putty command line tool similar to ssh that you can get from here

The Powershell  script can call the Plink.exe executable this way:

$sshcommand = & .\plink.exe unixhost -load unixhostsession "mkdir testfolder/testsubfolder;"


$sshcommand = & .\plink.exe unixhost -load unixhostsession "chmod 2750 /testfolder/testsubfolder;"

or even:

$sshcommand = & .\plink.exe unixhost -load unixhostsession "useradd testuser -d /testuser/workshop/home"

As you can understand any command can be fired with Plink.

Of course you can use Powershell variables inside these commands: 

$unixhostname = "sysx.yourcompany.com"
$folder1 = "testfolder"
$folder2 = "testsubfolder"
$sshcommand = & .\plink.exe $unixhostname -load unixhostsession "mkdir $folder1/$folder2;"

In these examples we are using the pretty useful -load switch, which is used by plink to load a saved Putty session. In this case the credentials (username and password, or username and key) are retrieved by Plink from the session named 'unixhostsession'. The session parameters are stored in the Windows Registry under the following registry key:


Remark also the use of the Powershell Call operator (the ampersand, &), which is used to lanch any exe/script.

Last but not least, know that you can concatenate commands using a semi-colon. Just be sure to enclose everything in quotes.

1 comment:

  1. Great explanation and very very useful to me!


Related Posts Plugin for WordPress, Blogger...