Tuesday, February 16, 2016

SSH via Powershell

In hosting environments, you rarely see only one flavor of operating system, so to be able to manage linux systems with Powershell via SSH is a big help. With Windows Server 2016, SSH connectivity will be built in, but until that time you can quite easily get it right now.

Step 1:
Go to https://sshnet.codeplex.com and download the .Net 4.0 binary from the downloads section and place the "Renci.SshNet.dll" file somewhere where you can access it. In my example I put it in C:\Scripts

Most likely Chrome will ask you whether it is safe to download, obviously say "Keep":







Step 2:
Go to the file, rightclick and select Properties, then unblock the file.



Step 3:
Here comes the example code. Quick explanation: First you load the DLL, then you create an object with the DLL file (I'm sure there's a technical programmy way of saying this, but I have no clue), then you suddenly have all these cool features like "Connect" and "RunCommand". It is not an interactive thing (as far as I know), and you only have a single command you can run, so you can't create a scriptblock and run it all at once.

#Load the SSHNet Library
[void][reflection.assembly]::LoadFrom( (Resolve-Path "C:\Scripts\Renci.SshNet.dll") )

#The variables you need to log on
$server = "Server01"
$login = "someuser"
$password = "somepassword"


#Call the SSHNet Library as an object
$SshClient = New-Object Renci.SshNet.SshClient($server, 22, $login, $password)
#Connect to client using SSH
  $SshClient.Connect()
    
   if ($SshClient.IsConnected) {
    Write-Host "Connected to " $server
    #Run the command on the linux host
    $cmd = $SshClient.RunCommand('ls -l')
    
    if($cmd.Result -ne '')
    {
        Write-Host Output from $server
        Write-Host $cmd.Result
    }
    
  }
$SshClient.Disconnect()
$SshClient.Dispose()

Which gives the following output:

Connected to  Server01
Output from Server01
total 12
-rw-r--r-- 1 Akos users 136 Feb 21  2008 local.cshrc
-rw-r--r-- 1 Akos users 157 Feb 21  2008 local.login
-rw-r--r-- 1 Akos users 174 Feb 21  2008 local.profile

Of course this is a simple example, but you can load in a CSV file with server, login and password info, and then have a command run on however many servers as you want. It's always fun being able to tell your boss that you're doing that thing on 50 servers, and then getting a cup of tea while your script is doing your work for you. This SSHNet client can also upload files using sftp but I haven't tried that yet.

No comments:

Post a Comment