Wednesday 4 July 2012

SSH.Net - Powershell

Thanks to SSH.Net lib, you can easily SSH into a linux server from powershell, upload/download files and run commands:
The following will create a folder in the users home called TestFolder, upload a file to that folder, then runs a command deleting teh folder:

 [parameter(Mandatory = $true)] [string] $serverName,
 [parameter(Mandatory = $true)] [string] $userName,
 [parameter(Mandatory = $true)] [string] $password

$sourceFile = "c:\Scripts\test.txt"
$destFile = "test.txt"
$destFolder = "/home/$userName/TestFolder"
$sshclient = New-Object Renci.SshNet.SshClient($serverName,$userName,$password )
if ($sshclient.IsConnected){
 $sftp = New-Object Renci.SshNet.SftpClient($sshclient.ConnectionInfo)
 if ($sftp.IsConnected){
  if (!$sftp.Exists($destFolder)){
  $sftp.UploadFile([System.IO.File]::OpenRead($sourceFile), $destFile)
  write-host "File Exists " $([bool](($sftp.ListDirectory(".") | select Name) -match "test.txt"))
 $o = $sshclient.RunCommand("rm /home/$userName/TestFolder -R")

No comments:

Post a Comment