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

Route Socket Connections through an SSH Object

See more Socket/SSL/TLS Examples

Demonstrates Socket.UseSsh, which configures a socket to route subsequent Connect calls through an already connected and authenticated Ssh object using SSH port forwarding.

Background. After UseSsh, the destination host and port passed to Connect are reached through the SSH tunnel rather than by a direct TCP connection. This is one of several SSH-tunneling approaches the Socket class supports.

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

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

procedure RunDemo;
var
  success: Boolean;
  ssh: TSsh;
  sshPassword: string;
  socket: TSocket;
  bTls: Boolean;
  maxWaitMs: Integer;

begin
  success := False;

  ssh := TSsh.Create;

  //  Connect and authenticate a standalone SSH object.
  success := ssh.Connect('ssh.example.com',22);
  if (success = False) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  //  The SSH password should come from a secure source rather than being hard-coded.
  sshPassword := 'mySshPassword';
  success := ssh.AuthenticatePw('sshUser',sshPassword);
  if (success = False) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  socket := TSocket.Create;

  //  Route subsequent Connect calls through the already connected and authenticated SSH object.  The
  //  destination is reached by SSH port forwarding rather than by a direct TCP connection.
  success := socket.UseSsh(ssh);
  if (success = False) then
    begin
      WriteLn(socket.LastErrorText);
      Exit;
    end;

  //  Connect to the destination through the SSH tunnel.
  bTls := False;
  maxWaitMs := 5000;
  success := socket.Connect('db.internal',5432,bTls,maxWaitMs);
  if (success = False) then
    begin
      WriteLn(socket.LastErrorText);
      Exit;
    end;
  WriteLn('Connected to the destination through the SSH tunnel.');


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