PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkSsh.pb"
Procedure ChilkatExample()
success.i = 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.
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
channelNum.i = CkSsh::ckOpenSessionChannel(ssh)
If channelNum < 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
EndIf
success = CkSsh::ckSendReqExec(ssh,channelNum,"grep -q root /etc/passwd")
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
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.
CkSsh::setCkReadTimeoutMs(ssh, 15000)
success = CkSsh::ckChannelReceiveToClose(ssh,channelNum)
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
EndIf
; Retrieve the exit status immediately, before calling unrelated SSH methods or releasing the
; channel, because the completed channel record can be discarded.
If CkSsh::ckChannelReceivedExitStatus(ssh,channelNum)
exitStatus.i = CkSsh::ckGetChannelExitStatus(ssh,channelNum)
Debug "Exit status: " + Str(exitStatus)
; By convention, 0 means the remote command succeeded.
If exitStatus = 0
Debug "The remote command succeeded."
Else
Debug "The remote command reported a failure."
EndIf
EndIf
CkSsh::ckDisconnect(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
EndProcedure