Sample code for 30+ languages & platforms
PureBasic

Start Concurrent SSH Commands with QuickCmdSend

See more SSH Examples

Demonstrates the Chilkat Ssh.QuickCmdSend method, which starts a remote command and immediately returns its channel number. The only argument is the command line. Internally it opens a session channel and sends an exec request.

Background: Because it returns without waiting, several commands can run concurrently over one authenticated connection — far faster than running them one after another when each has latency or slow work to do. Pair it with QuickCmdCheck, which reports commands as they finish, so results can be collected in completion order rather than the order they were started.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkSsh.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the Ssh.QuickCmdSend method, which starts a remote command and immediately
    ;  returns its channel number.  The only argument is the command line.  Because it returns
    ;  right away, several commands can run concurrently on the same SSH connection.

    ssh.i = CkSsh::ckCreate()
    If ssh.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    sshPort.i = 22
    success = CkSsh::ckConnect(ssh,"ssh.example.com",sshPort)
    If success = 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    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.
    password.s = "mySshPassword"

    success = CkSsh::ckAuthenticatePw(ssh,"mySshLogin",password)
    If success = 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    ;  Start three commands without waiting for any of them to finish.
    channel1.i = CkSsh::ckQuickCmdSend(ssh,"sleep 2; echo first done")
    If channel1 < 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    channel2.i = CkSsh::ckQuickCmdSend(ssh,"echo second done")
    If channel2 < 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    channel3.i = CkSsh::ckQuickCmdSend(ssh,"sleep 1; echo third done")
    If channel3 < 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    Debug "Started three concurrent commands."

    ;  Use QuickCmdCheck to collect the results as each command completes.

    CkSsh::ckDisconnect(ssh)


    CkSsh::ckDispose(ssh)


    ProcedureReturn
EndProcedure