Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Open a Forwarded Channel through an SSH Tunnel
See more Socket/SSL/TLS Examples
Demonstrates Socket.SshNewChannel, which opens a port-forwarded channel through an authenticated SSH tunnel to a destination host and port, populating a Socket with the connected channel.
Background. Set the ssl argument to true to establish TLS to the destination inside the SSH tunnel. The returned channel socket is then used to send and receive with the destination.
Chilkat Pascal (Lazarus/Delphi) Downloads
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.Socket;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
socket: TSocket;
sshPassword: string;
bTls: Boolean;
maxWaitMs: Integer;
channel: TSocket;
begin
success := False;
socket := TSocket.Create;
// Connect to the SSH server and initialize an SSH tunneling session. Port 22 is conventional but
// not required.
success := socket.SshOpenTunnel('ssh.example.com',22);
if (success = False) then
begin
WriteLn(socket.LastErrorText);
Exit;
end;
// Authenticate the SSH session before opening forwarded channels.
// The SSH password should come from a secure source rather than being hard-coded.
sshPassword := 'mySshPassword';
success := socket.SshAuthenticatePw('sshUser',sshPassword);
if (success = False) then
begin
WriteLn(socket.LastErrorText);
Exit;
end;
// Open a port-forwarded channel through the authenticated SSH tunnel to the destination host and
// port, populating a Socket with the connected channel. Set the 3rd argument to True to establish
// TLS to the destination inside the tunnel.
bTls := False;
maxWaitMs := 20000;
channel := TSocket.Create;
success := socket.SshNewChannel('db.internal',5432,bTls,maxWaitMs,channel);
if (success = False) then
begin
WriteLn(socket.LastErrorText);
Exit;
end;
// Use the channel socket to send and receive with the destination through the tunnel.
WriteLn('Forwarded channel opened to the destination.');
socket.Free;
channel.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.