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

SSH Exec (Execute Command Line)

See more SSH Examples

Demonstrates running a single command on an SSH server with an exec request and retrieving its output. The example connects, authenticates, opens a session channel, sends the command, reads until the server closes the channel, and then checks the exit status.

Background: exec is the workhorse of SSH automation: it runs one command and the server closes the channel when the command exits, which is a definitive end-of-output signal. No PTY is involved, so the shell runs non-interactively — no prompt, no echoed input, no ANSI escape codes — giving clean, parseable output. Remember that an accepted exec request only means the request was accepted; the command's own success is reported through the channel exit status. Command syntax depends on the remote shell, which is the user's default shell on Linux/UNIX and usually CMD.EXE on Windows SSH servers.

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;
  hostname: string;
  port: Integer;
  password: string;
  channelNum: Integer;
  cmdOutput: string;

begin
  success := False;

  //  This example requires the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  //  Demonstrates running a single command on an SSH server with an exec request and retrieving
  //  its output.  An exec request runs one command and the server closes the channel when it
  //  finishes -- no PTY and no shell prompt are involved, so the output is clean and parseable.

  ssh := TSsh.Create;

  //  The hostname may be a hostname or an IP address.
  hostname := 'ssh.example.com';
  port := 22;
  success := ssh.Connect(hostname,port);
  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;

  //  Open a session channel.  Several session channels may be open at once on one connection.
  channelNum := ssh.OpenSessionChannel();
  if (channelNum < 0) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  //  The command syntax depends on the remote system's shell.  On Linux/UNIX it is typically the
  //  user's default shell; on Windows SSH servers it is usually CMD.EXE.
  //    Linux/UNIX:  "ls -l /tmp"        or  "cd /etc; ls -la"
  //    Windows:     "dir"               or  "\"cd \\temp&&dir\""
  success := ssh.SendReqExec(channelNum,'ls -l /tmp');
  if (success = False) then
    begin
      WriteLn(ssh.LastErrorText);
      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.
  ssh.ReadTimeoutMs := 15000;

  //  Read the output until the server sends channel close, which happens when the command exits.
  success := ssh.ChannelReceiveToClose(channelNum);
  if (success = False) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  cmdOutput := ssh.GetReceivedText(channelNum,'utf-8');
  if (ssh.LastMethodSuccess = False) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;
  WriteLn(cmdOutput);

  //  An accepted exec request does not mean the command succeeded.  Check the exit status.
  if (ssh.ChannelReceivedExitStatus(channelNum)) then
    begin
      WriteLn('Exit status: ' + ssh.GetChannelExitStatus(channelNum));
    end;

  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.