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/




Python Script To Connect to remote server and run rails tasks

We need to import paramiko python2 package and it's dependent packages like bcrypt and PyNaCI

Here is the python2 script to connect ssh

import paramiko
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='xxxx',username='xxxx',password='xxxx'', allow_agent=False,look_for_keys=False)
ssh_client.invoke_shell()
stdin,stdout,stderr=ssh_client.exec_command("export PATH=/home/xxx/.rbenv/shims:/home/xxx/.rbenv/bin:/home/agwebadmin/bin:/home/xxx/.local/bin:/home/xxx/.rbenv/shims:/home/xxx/.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/HotDesk; rake sunspot:solr:reindex")
print stdout.read()
print stderr.read()
ssh_client.close()

To get ruby path we need to run command $which ruby