Tuesday 10 September 2019

PowerShell script to connect to connect to remote

We need to install the Posh-SSH module

Here is the script written using Posh-SSH module

param(
    $Computername = "xxxxx",
    $Username = "xxxx",
    $Password = "xxx",
    $Port = 22,
    $KeyfilePath = ""
    # $AutoUpdateFingerprint = $False
)
# function This-FingerPrintUpdate(){
#     Write-Output "calling fingerprint fun.."
#     if($AutoUpdateFingerprint)
#     { Remove-SSHTrustedHost $Computername }
# }
function This-GetSSHCommandOutput(){
# Create new session and execute the command given
$SecPasswd   = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($Username, $SecPasswd)
    $Session = New-SSHSession -Computername $Computername -Credential $Credentials -Port $Port -Acceptkey
    $Output = (Invoke-SSHCommand -Command 'export PATH=/home/xxx/.rbenv/shims:/home/agwebadmin/.rbenv/bin:/home/xxx/bin:/home/agwebadmin/.local/bin:/home/xxx/.rbenv/shims:/home/xx/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin; export RAILS_ENV=production; ruby -v; cd current/hotDesks; rake sunspot:solr:reindex' -SSHSession $Session).Output
    # Remove the session after we're done
    Remove-SSHSession -Name $Session | Out-Null
    # return the actual output
    Write-Output $Output
}
# This-FingerPrintUpdate
This-GetSSHCommandOutput

Referrences:

https://www.powershellmagazine.com/2014/07/03/posh-ssh-open-source-ssh-powershell-module/




No comments:

Post a Comment