Invoke-SSH

This one is really usefull. Open a ssh session and run commands from PowerShell with PLink
Love it!

Function Invoke-SSH {
Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)

$Target = $Username + '@' + $Hostname
$plinkoptions = "-ssh $Target -pw $Password"

#Build ssh Commands
$CommandArray += "exit"
$remoteCommand = ""
$CommandArray | % {$remoteCommand += [string]::Format('{0}; ', $_) }

#plist prompts to accept client host key. This section will login and accept the host key then logout.
if($ConnectOnceToAcceptHostKey)
{
$PlinkCommand  = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions )
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
}

#format plist command
$PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)

#ready to run the following command
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
$msg
}
#Plink path, credentials and target server definition
$PlinkAndPath = "C:\Program Files (x86)\PuTTY\plink.exe"
$Username = "root"
$Password = "password"
$Hostname = "computername"

#Commands to execute on the remote ssh host.
$Commands += "show rserver computer detail"
$Commands += "exit"
$Commands += "exit"

Invoke-SSH -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands

Leave a Reply

Scroll to Top