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

Authenticate an SSH Tunnel with a Private Key

See more Socket/SSL/TLS Examples

Demonstrates Socket.SshAuthenticatePk, which authenticates an SSH tunnel session using a private key loaded into an SshKey object. Call SshOpenTunnel first.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The SSH server must have the corresponding public key authorized for the account. If the private key is encrypted, set the SshKey.Password property before loading it.

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.SshKey,
  Chilkat.Socket;

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

procedure RunDemo;
var
  success: Boolean;
  socket: TSocket;
  sshKey: TSshKey;
  keyText: string;

begin
  success := False;

  socket := TSocket.Create;

  success := socket.SshOpenTunnel('ssh.example.com',22);
  if (success = False) then
    begin
      WriteLn(socket.LastErrorText);
      Exit;
    end;

  //  Load the SSH private key.  The file path is relative to the application's current working
  //  directory.  If the key is encrypted, set the SshKey.Password property before calling
  //  FromOpenSshPrivateKey.
  sshKey := TSshKey.Create;
  keyText := sshKey.LoadText('qa_data/id_ed25519');
  if (sshKey.LastMethodSuccess = False) then
    begin
      WriteLn(sshKey.LastErrorText);
      Exit;
    end;
  success := sshKey.FromOpenSshPrivateKey(keyText);
  if (success = False) then
    begin
      WriteLn(sshKey.LastErrorText);
      Exit;
    end;

  //  Authenticate the SSH tunnel session using public-key authentication.  The SSH server must have the
  //  corresponding public key authorized for the account.
  success := socket.SshAuthenticatePk('sshUser',sshKey);
  if (success = False) then
    begin
      WriteLn(socket.LastErrorText);
      Exit;
    end;
  WriteLn('SSH public-key authentication succeeded.');


  socket.Free;
  sshKey.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.