Sample code for 30+ languages & platforms
Lianja

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 Lianja Downloads

Lianja
llSuccess = .F.

//  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 .T..

loSsh = createobject("CkSsh")

lnSshPort = 22
llSuccess = loSsh.Connect("ssh.example.com",lnSshPort)
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    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.
lcPassword = "mySshPassword"

llSuccess = loSsh.AuthenticatePw("mySshLogin",lcPassword)
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

lnChannelNum = loSsh.OpenSessionChannel()
if (lnChannelNum < 0) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

llSuccess = loSsh.SendReqExec(lnChannelNum,"grep -q root /etc/passwd")
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    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.
loSsh.ReadTimeoutMs = 15000

llSuccess = loSsh.ChannelReceiveToClose(lnChannelNum)
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    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 (loSsh.ChannelReceivedExitStatus(lnChannelNum)) then
    lnExitStatus = loSsh.GetChannelExitStatus(lnChannelNum)
    ? "Exit status: " + str(lnExitStatus)

    //  By convention, 0 means the remote command succeeded.
    if (lnExitStatus = 0) then
        ? "The remote command succeeded."
    else
        ? "The remote command reported a failure."
    endif

endif

loSsh.Disconnect()


release loSsh