question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Assistance needed: Capturing $stream.Read() response without issuing "blind" Start-Sleep command afterwards

See original GitHub issue

Considering 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:closed
  • Created a year ago
  • Comments:20 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
mkanetcommented, Aug 29, 2022

@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:

do {
    $session = New-SSHSession -ComputerName $DeviceName -AcceptKey -Credential $Credential -force
} until ($session -ne $null -and $session.Connected)

All issues are now resolved. Thanks again for your time!

0reactions
darkoperatorcommented, Oct 11, 2022

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

On Aug 25, 2022, at 8:41 AM, MKANET @.***> wrote:

Looked at Expect() in Renci source

This is definitely not what you need EndExpect() it’s a async companion to BeginExpect()

And Expect() itself is equal to Read() and match(), i.e. it wait for some string or regex and drop all intermediate output

I think I’ll need to wait for darkoperator for this. I wasn’t able to figure out an effective way to take advantage of the available methods and properties for stream to wait the minimum amount of time between $stream.Write(“$Command``n”) and $stream.read()

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.

Read more comments on GitHub >

github_iconTop Results From Across the Web

JavaScript fetch - Failed to execute 'json' on 'Response'
I met this error too but found out it is not related to the state of Response, the real problem is that you...
Read more >
Execute a build step based on a condition (fixed for server ...
Now, we understand that other CI servers can have conditional steps, but then it means features that I described are either not implemented...
Read more >
WSUS Just Sucks. Period. : r/sysadmin
I have only seen one broken WMI system on Win10 and it got reimaged after a tech spent 3 hours trying to fix...
Read more >
Attacker's Mindset – Cyber Security and Related Topics – all ...
Recently I've been wanting to dive into anomaly detection and classification problems – I'm starting this by exploring a binary-classification issue ...
Read more >
Resolved Problems for Service Packs 1 - 6
Whenever a method permission was created from the Administration Console in the examples domain and the server was restarted, WebLogic Server was throwing...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found