PowerShell - SSH From windows

Published: 03 February 2022
on channel: Mr Automation
1,191
23

(How to run a command on Linux/Unix/network device via ssh from windows)

In this video I demonstrate how you can connect to a SSH based device from a windows box and execute command remotely on them.
The script is very simple, though quite powerful.
I added the use of a simple input file in csv format, so you can run it against multiple systems if you like.

*powershell
*learn powershell
*automation
*learn automation
*state.show_sls
*windows
*linux
*windows powershell

Code :

#$PSVersionTable
#find-module posh-ssh
#install-module Posh-SSH
#get-module Posh-SSH #| select ExportedCommands
$p = "MyPass01"
$secpass = $p | ConvertTo-SecureString -AsPlainText -Force
$clientCreds = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList "root", $secpass
$SSHsession = New-SSHSession -ComputerName l01.home.local -acceptkey -credential $clientCreds -ConnectionTimeout 30
$o = Invoke-SSHCommand -SSHSession $SSHsession -Command "ls /"
$o
$o.Output #this is the output property you get back
Remove-SSHSession -SSHSession $SSHsession | Out-Null

foreach($item in import-csv .\input.csv){
Write-Warning "starting with $($item.hostname)"
$secpass = $item.password | ConvertTo-SecureString -AsPlainText -Force
$clientCreds = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $item.username, $secpass
$SSHsession = New-SSHSession -ComputerName $item.hostname -acceptkey -credential $clientCreds -ConnectionTimeout 30
$o = Invoke-SSHCommand -SSHSession $SSHsession -Command "$($item.commandtorun)"
$o.Output #this is the output property you get back
Start-Sleep -Seconds 3
Remove-SSHSession -SSHSession $SSHsession | Out-Null
}


On this page of the site you can watch the video online PowerShell - SSH From windows with a duration of hours minute second in good quality, which was uploaded by the user Mr Automation 03 February 2022, share the link with friends and acquaintances, this video has already been watched 1,191 times on youtube and it was liked by 23 viewers. Enjoy your viewing!