Home > Powershell > Invoking SSH commands using powershell (kinda)

Invoking SSH commands using powershell (kinda)

Sometimes, you need to fire SSH commands from a Powershell session.
This is quite quick and easy if you have the right tools.

First of all, get the Posh-SSH cmdlets off github:

Install this like any other module (Drop it in your PSModulePath – else amend the code below to import the module from wherever you would like to execute it)
Now simply fire away using the module.

clever work (none of the credit to me)

I’ve used this for invoking SSH commands against ESX hosts, Dell iDracs and other SSH devices. Simple and quite reliable. I find it far more consistent than plink.exe etc

# Quick and untested copy of what you need:

Import-Module Posh-SSH

# Create Pwd (this saves a file copy)
# read-host -assecurestring | convertfrom-securestring | out-file $env:userprofile\$env:username.txt

# Retrieve info from file previously created under user profile
$username = "username@domain.net.intra"
$password = get-content $env:userprofile\$env:username.txt | convertto-securestring
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password

# Create SSH Session
$ssh = New-SSHSession -ComputerName $vmhost -Credential $credential -AcceptKey 1

# Invoke SSH command and capture output as string (you can return the full object if you like, I just needed the string Out)
$ret = $(Invoke-SSHCommand -SSHSession $ssh -Command "racadm getconfig -g cfgUserAdmin -i 2").Output

# return object is a String - if you want it as an array of strings for each row returned
$ret = $ret.split("`n")

# Clean up your mess
Remove-SSHSession -SSHSession $ssh
Remove-variable ssh

Categories: Powershell Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.