Xbase++
Xbase++
SSH Parallel Remote Commands on a Single Server
See more SSH Examples
Demonstrates running several commands in parallel on one SSH server and collecting each command's output as it finishes. QuickCmdSend starts each command and returns immediately; QuickCmdCheck reports them as they complete.
Background: Because SSH multiplexes channels, several commands can run at once over one authenticated connection — far faster than running them one after another when each involves waiting. Results arrive in completion order rather than the order the commands were started, so the loop keys off the returned channel number. Distinguish the two negative returns carefully:
-1 means "still working, ask again," while -2 means nothing remains to collect or the connection failed.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSsh
LOCAL nPort
LOCAL cPassword
LOCAL nChannel1
LOCAL nChannel2
LOCAL nChannel3
LOCAL nPollTimeoutMs
LOCAL nNumFinished
LOCAL nChannel
LOCAL cCmdOutput
nSuccess := 0
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Demonstrates running several commands in parallel on a single SSH server and collecting each
// command's output as it finishes.
oSsh := CreateObject("Chilkat.Ssh")
nPort := 22
nSuccess := oSsh:Connect("ssh.example.com", nPort)
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
// QuickCmdSend starts a command and returns immediately, so all three run concurrently, each on
// its own session channel.
nChannel1 := oSsh:QuickCmdSend("df")
IF (nChannel1 < 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
nChannel2 := oSsh:QuickCmdSend("date")
IF (nChannel2 < 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
nChannel3 := oSsh:QuickCmdSend("echo hello world")
IF (nChannel3 < 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
// Collect the results. QuickCmdCheck returns the channel number of a completed command,
// -1 when commands are still pending but none finished within the timeout, or -2 when nothing
// remains to be checked (or an error occurred).
nPollTimeoutMs := 50
nNumFinished := 0
DO WHILE nNumFinished < 3
nChannel := oSsh:QuickCmdCheck(nPollTimeoutMs)
IF (nChannel == -2)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
IF (nChannel >= 0)
? "---- channel " + Str(nChannel) + " finished ----"
cCmdOutput := oSsh:GetReceivedText(nChannel, "utf-8")
IF (oSsh:LastMethodSuccess == 0)
? oSsh:LastErrorText
oSsh:destroy()
RETURN
ENDIF
? cCmdOutput
nNumFinished := nNumFinished + 1
ENDIF
ENDDO
oSsh:Disconnect()
oSsh:destroy()