Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Run a Single SSH Command and Get the Output

See more SSH Examples

Demonstrates the Chilkat Ssh.QuickCommand method, which runs one noninteractive remote command and returns its stdout as text. The first argument is the command and the second is the charset used to decode the output. Internally it opens a session channel, sends an exec request, and receives the output through EOF.

Background: This collapses the whole open-channel / exec / receive / retrieve sequence into a single call, and it is the right choice for the common case of "run one command and give me the output." Because no PTY is involved the output is clean and parseable, with no prompt or echoed input. Reach for the individual channel methods only when you need stderr separately, the exit status, or an interactive session.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Ssh;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  ssh: TSsh;
  sshPort: Integer;
  password: string;
  output: string;

begin
  success := False;

  //  Demonstrates the Ssh.QuickCommand method, which runs one noninteractive remote command and
  //  returns its stdout as text.  The 1st argument is the command and the 2nd is the charset used
  //  to decode the output.  Internally it opens a session channel, sends an exec request, and
  //  receives the output through EOF.

  ssh := TSsh.Create;

  sshPort := 22;
  success := ssh.Connect('ssh.example.com',sshPort);
  if (success = False) then
    begin
      WriteLn(ssh.LastErrorText);
      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 := ssh.AuthenticatePw('mySshLogin',password);
  if (success = False) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  //  Run a single command and collect its output in one call.
  output := ssh.QuickCommand('uname -a','utf-8');
  if (ssh.LastMethodSuccess = False) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;
  WriteLn(output);

  ssh.Disconnect();


  ssh.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.