Delphi DLL
Delphi DLL
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 Delphi DLL Downloads
var
success: Boolean;
ssh: HCkSsh;
sshPort: Integer;
password: PWideChar;
channelNum: Integer;
exitStatus: Integer;
begin
success := False;
// 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 := CkSsh_Create();
sshPort := 22;
success := CkSsh_Connect(ssh,'ssh.example.com',sshPort);
if (success = False) then
begin
Memo1.Lines.Add(CkSsh__lastErrorText(ssh));
Exit;
end;
// 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 := 'mySshPassword';
success := CkSsh_AuthenticatePw(ssh,'mySshLogin',password);
if (success = False) then
begin
Memo1.Lines.Add(CkSsh__lastErrorText(ssh));
Exit;
end;
channelNum := CkSsh_OpenSessionChannel(ssh);
if (channelNum < 0) then
begin
Memo1.Lines.Add(CkSsh__lastErrorText(ssh));
Exit;
end;
success := CkSsh_SendReqExec(ssh,channelNum,'grep -q root /etc/passwd');
if (success = False) then
begin
Memo1.Lines.Add(CkSsh__lastErrorText(ssh));
Exit;
end;
// 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_putReadTimeoutMs(ssh,15000);
success := CkSsh_ChannelReceiveToClose(ssh,channelNum);
if (success = False) then
begin
Memo1.Lines.Add(CkSsh__lastErrorText(ssh));
Exit;
end;
// Retrieve the exit status immediately, before calling unrelated SSH methods or releasing the
// channel, because the completed channel record can be discarded.
if (CkSsh_ChannelReceivedExitStatus(ssh,channelNum)) then
begin
exitStatus := CkSsh_GetChannelExitStatus(ssh,channelNum);
Memo1.Lines.Add('Exit status: ' + IntToStr(exitStatus));
// By convention, 0 means the remote command succeeded.
if (exitStatus = 0) then
begin
Memo1.Lines.Add('The remote command succeeded.');
end
else
begin
Memo1.Lines.Add('The remote command reported a failure.');
end;
end;
CkSsh_Disconnect(ssh);
CkSsh_Dispose(ssh);