SQL Server
SQL Server
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 SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
DECLARE @socket int
EXEC @hr = sp_OACreate 'Chilkat.Socket', @socket OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- Connect to the SSH server and initialize an SSH tunneling session. Port 22 is conventional but
-- not required.
EXEC sp_OAMethod @socket, 'SshOpenTunnel', @success OUT, 'ssh.example.com', 22
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @socket, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @socket
RETURN
END
-- Authenticate the SSH session before opening forwarded channels.
-- The SSH password should come from a secure source rather than being hard-coded.
DECLARE @sshPassword nvarchar(4000)
SELECT @sshPassword = 'mySshPassword'
EXEC sp_OAMethod @socket, 'SshAuthenticatePw', @success OUT, 'sshUser', @sshPassword
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @socket, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @socket
RETURN
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 1 to establish
-- TLS to the destination inside the tunnel.
DECLARE @bTls int
SELECT @bTls = 0
DECLARE @maxWaitMs int
SELECT @maxWaitMs = 20000
DECLARE @channel int
EXEC @hr = sp_OACreate 'Chilkat.Socket', @channel OUT
EXEC sp_OAMethod @socket, 'SshNewChannel', @success OUT, 'db.internal', 5432, @bTls, @maxWaitMs, @channel
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @socket, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @socket
EXEC @hr = sp_OADestroy @channel
RETURN
END
-- Use the channel socket to send and receive with the destination through the tunnel.
PRINT 'Forwarded channel opened to the destination.'
EXEC @hr = sp_OADestroy @socket
EXEC @hr = sp_OADestroy @channel
END
GO