Sample code for 30+ languages & platforms
Xbase++

Get the Exit Status of a Remote SSH Command

See more SSH Examples

Demonstrates the Chilkat Ssh.GetChannelExitStatus method, which returns the remote process exit status for a channel. The only argument is the channel number. Call it only after ChannelReceivedExitStatus returns true.

Background: The exit status is how you learn whether a remote command actually succeeded — recall that a successful exec request only means the request was accepted. By Unix convention 0 means success and any nonzero value indicates a failure. Retrieve it promptly after the receive operation and before calling unrelated SSH methods or releasing the channel, since the completed channel record can be discarded.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oSsh
LOCAL nSshPort
LOCAL cPassword
LOCAL nChannelNum
LOCAL nExitStatus

nSuccess := 0

//  Demonstrates the Ssh.GetChannelExitStatus method, which returns the remote process exit
//  status for a channel.  The only argument is the channel number.  Call it only after
//  ChannelReceivedExitStatus returns 1.

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

nChannelNum := oSsh:OpenSessionChannel()
IF (nChannelNum < 0)
    ? oSsh:LastErrorText
    oSsh:destroy()
    RETURN
ENDIF

nSuccess := oSsh:SendReqExec(nChannelNum, "grep -q root /etc/passwd")
IF (nSuccess == 0)
    ? oSsh:LastErrorText
    oSsh:destroy()
    RETURN
ENDIF

//  IMPORTANT: Set a read timeout.  ReadTimeoutMs defaults to 0, which means no limit -- without
//  it, this call waits forever if the server never sends channel close.
oSsh:ReadTimeoutMs := 15000

nSuccess := oSsh:ChannelReceiveToClose(nChannelNum)
IF (nSuccess == 0)
    ? oSsh:LastErrorText
    oSsh:destroy()
    RETURN
ENDIF

//  Retrieve the exit status immediately, before calling unrelated SSH methods or releasing the
//  channel, because the completed channel record can be discarded.
IF (oSsh:ChannelReceivedExitStatus(nChannelNum))
    nExitStatus := oSsh:GetChannelExitStatus(nChannelNum)
    ? "Exit status: " + Str(nExitStatus)

    //  By convention, 0 means the remote command succeeded.
    IF (nExitStatus == 0)
        ? "The remote command succeeded."
    ELSE
        ? "The remote command reported a failure."
    ENDIF

ENDIF

oSsh:Disconnect()

oSsh:destroy()