Xbase++
Xbase++
Collect Completed SSH Commands with QuickCmdCheck
See more SSH Examples
Demonstrates the Chilkat Ssh.QuickCmdCheck method, which waits for any command started by QuickCmdSend to complete. The only argument is the poll timeout in milliseconds; 0 performs a nonblocking check. It returns the channel number of a completed command, -1 when commands are still pending but none finished before the timeout, or -2 when no quick commands remain or an error occurred.
Background: This is the collection half of the concurrent pattern. Each completed channel is reported only once, so looping until
-2 drains every outstanding command exactly once. Distinguish the two negative values carefully: -1 simply means "still working, ask again," while -2 means there is nothing left to wait for — or that the connection failed, so check LastErrorText when the distinction matters. Manually opened exec channels are not reported here.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSsh
LOCAL nSshPort
LOCAL cPassword
LOCAL nChannel1
LOCAL nChannel2
LOCAL nPollTimeoutMs
LOCAL nCompletedChannel
LOCAL cOutput
nSuccess := 0
// Demonstrates the Ssh.QuickCmdCheck method, which waits for any command started by
// QuickCmdSend to complete. The only argument is the poll timeout in milliseconds; 0 performs
// a nonblocking check.
oSsh := CreateObject("Chilkat.Ssh")
nSshPort := 22
nSuccess := oSsh:Connect("ssh.example.com", nSshPort)
IF (nSuccess == 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
cPassword := "mySshPassword"
nSuccess := oSsh:AuthenticatePw("mySshLogin", cPassword)
IF (nSuccess == 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
// Start two commands that will finish at different times.
nChannel1 := oSsh:QuickCmdSend("sleep 2; echo first done")
IF (nChannel1 < 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
nChannel2 := oSsh:QuickCmdSend("echo second done")
IF (nChannel2 < 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
// Collect the results as they complete. The return value is the channel number of a completed
// command, -1 if commands are still pending but none finished before the timeout, or -2 when
// no quick commands remain (or an error occurred).
nPollTimeoutMs := 5000
nCompletedChannel := oSsh:QuickCmdCheck(nPollTimeoutMs)
DO WHILE nCompletedChannel != -2
IF (nCompletedChannel >= 0)
cOutput := oSsh:GetReceivedText(nCompletedChannel, "utf-8")
IF (oSsh:LastMethodSuccess == 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
? "Channel " + Str(nCompletedChannel) + " finished: " + cOutput
ENDIF
IF (nCompletedChannel == -1)
? "Still waiting for a command to finish..."
ENDIF
nCompletedChannel := oSsh:QuickCmdCheck(nPollTimeoutMs)
ENDDO
? "All quick commands have been collected."
oSsh:Disconnect()
oSsh:destroy()