1 year ago
#380115
MKANET
Posh-SSH script on Cisco devices
I made a Posh-SSH based script that will let me send commands to Cisco routers. It works great... except for a very specific case.
function Send-SSHCommand {
Param(
[Parameter(Mandatory=$true)]
[String]$Command,
[Parameter(Mandatory=$false)]
[string]$DeviceName = "CiscoRouter"
)
remove-variable Response -ErrorAction SilentlyContinue
Get-SSHSession | select SessionId | Remove-SSHSession | Out-Null
New-SSHSession -ComputerName $DeviceName -AcceptKey -Credential $Credential | Out-Null
$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
$stream.Write("$Command`n")
$ResponseRaw = $stream.Read()
$Response = $ResponseRaw -split "`r`n" | %{$_.trim()}
while (($Response[$Response.Count -1]) -ne "$DeviceName#") {
sleep -mill 60
$ResponseRaw = $stream.Read()
$Response = $ResponseRaw -split "`r`n" | %{$_.trim()}
}
Return $Response
}
Usage Examples that work correctly:
Send-SSHCommand "sh ip cache flow" -DeviceName "CiscoRouter1"
Send-SSHCommand "sho ip int bri | include Serial|NVRAM|Multilink1|manual" -DeviceName "CiscoRouter1"
Send-SSHCommand "sho bgp sum" -DeviceName "CiscoRouter1"
However, the script will hang indefinitely when I use a command like below on any device that doesn't return a respective result for the command. The script is expecting a result. So, when its executed on a device that doesn't return any information for a command, the script just hangs indefinitely:
Send-SSHCommand "sh flow monitor" -DeviceName "CiscoRouter2"
This is what it looks like on a device's console that doesn't have a respective result for sho flow monitor
:
CiscoRouter2#sh flow monitor
CiscoRouter2#
The script works perfectly in cases like below where there is information returned like below:
CiscoRouter1#sh flow monitor
Flow Monitor Traffic_INPUT:
Description: DDR-FO NetFlow
Flow Record: SER-INPUT
CiscoRouter1#
How can I write the while logic so it doesn't hang in cases where no information is returned from the command?
powershell
cisco
cisco-ios
posh-ssh
0 Answers
Your Answer