Simulating Linux SSH in PowerShell for ONTAP

There’s no native way in Windows of doing> ssh [user@]hostname command
So - as a curiosity - I thought I’d write the function. This works for NetApp Clustered Data ONTAP/ONTAP.

The Script

Save as say ssh.ps1 and import into your PowerShell session using . .\ssh.ps1 (dot space dot), then run in PowerShell as>
ssh [user@]hostname command


# The following function simulates the Linux SSH syntax in PowerShell for ...
# ... NetApp Clustered Data ONTAP, in conjunction with the Data ONTAP PSTK:
# > ssh [user@]hostname command
# It takes advantage of the NcCredential feature of the Data ONTAP PSTK ...
# ... use> Add-NcCredential CONTROLLER = Add credentials

Function SSH{
  ## GENERIC: LOAD THE DATA ONTAP PSTK ##
  If(!(Get-Module DataONTAP)){
    [Void](Import-Module DataONTAP -ErrorAction SilentlyContinue)
    If(!(Get-Module DataONTAP)){ "Failed to load DataONTAP PSTK!"; RETURN }
  }
 
  ## SCENARIO 1: No Argument/No 2nd Arg (No $Args[0]/No $Args[1]) ##
  If(!$Args[0]){ "SYNTAX ERROR: 0 arguments detected (2 expected)!"; RETURN }
  If(!$Args[1]){ "SYNTAX ERROR: 1 argument detected (2 expected)!"; RETURN }
 
  ## PROCESS INPUT $Arg[0] and $Arg[1] ##
  [System.Array]$Arg0 = $Args[0].Split("@")
  If($Arg0.Count -eq 2){
    [String]$User = $Arg0[0]
    [String]$Host = $Arg0[1]
  }elseif($Arg0.Count -eq 1){
    [String]$User = ""
    [String]$Host = $Arg0[0]
  }else{
    "SYNTAX ERROR: Too many @ in $Args[0]!"; RETURN
  }
 
  ## CHECK HOST CREDENTIAL ##
  $GetNcCred = Get-NcCredential $Host
  If(!$GetNcCred){
    "ERROR: No credentials for $Host in the NcCredentials cache. To add use> Add-NcCredential $Host"; RETURN
  }
  $NcCredUser = $GetNcCred.Credential.Username
  If($User -and ($NcCredUser -ne $User)){
    "ERROR: NcCredential for $Host uses user $NcCredUser and not $User. To add correct credential use> Add-NcCredential $Host"; RETURN
  }
 
  ## EXAMINE CurrentNcController ##     
  If($Global:CurrentNcController){
    If($Global:CurrentNcController.Name -ne $Host){ $Global:CurrentNcController = $Null}
    else{
      $TempUser = $Global:CurrentNcController.Credentials.Username
      $TempDomain = $Global:CurrentNcController.Credentials.Domain
      If($TempDomain){ $TempUser += ("\" + $TempDomain) }
      If($User -ne $TempUser){ $Global:CurrentNcController = $Null }
    }
  }
 
  ## CONNECT ##
  If(!$Global:CurrentNcController){
    [Void](Connect-NcController $Host -ErrorAction SilentlyContinue)
    If(!$Global:CurrentNcController){"ERROR: Failed to connnect to $Host!"; RETURN}
  }
 
  ## RUN COMMAND ##
  (Invoke-NcSsh $Args[1]).Value
}


Example

Image: Running SSH [user@]hostname command in PowerShell
Note: Not sure if it’s because I’m using a simulator, but this doesn’t run fast, the Invoke-NcSSH isn’t quick.

Comments