Assistance needed: Capturing $stream.Read() response without issuing "blind" Start-Sleep command afterwards
See original GitHub issueConsidering there are a couple of known issues with Cisco devices and Posh-SSH, I have to use SSH streams in Posh-SSH.
Hence, I created a PS function Send-SSHCommand
(below) which will send any sequence of commands to a Cisco device; and, return the output as FAST as possible.
Instead of putting a blind Start-Sleep 5
command after issuing $ResponseRaw = $stream.Read()
, I would like to use a clever way to wait the minimum amount of time (before reading the entire stream) by using some kind of while
command. For example: while (!($stream.EndExpect("$DeviceName#"))) { Start-Sleep 60 }
. I know that I can’t use the method .EndExpect
like that. But, I think you’ll at least understand my goal.
Note: The only thing I know for sure is that the end of the output ALWAYS ends with $DeviceName#
.
function Send-SSHCommand {
Param(
[Parameter(Mandatory=$true)]
[Array]$Commands,
[Parameter(Mandatory=$false)]
[string]$DeviceName
)
BEGIN {
$Final = @()
remove-variable Response -ErrorAction SilentlyContinue
Get-SSHSession | select SessionId | Remove-SSHSession | Out-Null
New-SSHSession -ComputerName $DeviceName -AcceptKey -Credential $Credential -ErrorAction SilentlyContinue | Out-Null
while ((Get-SSHSession).Host -ne $DeviceName) {
New-SSHSession -ComputerName $DeviceName -AcceptKey -Credential $Credential -ErrorAction SilentlyContinue | Out-Null
sleep -mill 500
}
$session = Get-SSHSession -Index 0
$stream = $session.Session.CreateShellStream("dumb", 0, 0, 0, 0, 1000)
$stream.Write("terminal Length 0`n")
sleep -mill 60
$stream.Read() | Out-Null
}
PROCESS {
foreach ($Command in $Commands)
{
$stream.Write("$Command`n")
Start-Sleep 5
# while (!($stream.EndExpect("$DeviceName#"))) { Start-Sleep 60 }
# while ($stream.DataAvailable -eq $true) { Start-Sleep 60 }
# $stream.WriteTimeout = 5000
$ResponseRaw = $stream.Read()
$Response = $ResponseRaw -split "`r`n" | %{$_.trim()}
$Response = $Response | ?{$_ -NotMatch "$DeviceName#"}
$Final += $Response
}
}
END {
Return $Final
$stream.Write("exit`n")
Remove-SSHSession -Index 0 | Out-Null
}
}
Command: Send-SSHCommand -DeviceName “Cisco-device01” -Commands "sho log | include Aug 2.*
Issue Analytics
- State:
- Created a year ago
- Comments:20 (10 by maintainers)
@MVKozlov EDIT: Update. I was able to finally use the “correct” way to use
New-SSHSession
every time. It works every time. I am now using the below code:All issues are now resolved. Thanks again for your time!
Actually expect was what I was going to recomment because it is what I use for sudo. Never dealt with an expired password. That is why I made this function https://github.com/darkoperator/Posh-SSH/blob/master/docs/Invoke-SSHStreamExpectSecureAction.md
Sent from my iPhone