Sample code for 30+ languages & platforms
Lua

Start an SSH Tunnel Listener (BeginAccepting)

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.BeginAccepting method, which creates and starts the local listener on the given port. The only argument is the listen port. Connect and authenticate first — clients accepted before authentication cannot be forwarded. The IsAccepting property reports whether the listener is running.

Background: This is the step that actually turns the object into a working tunnel: it spawns a background thread that accepts local TCP connections and forwards each through the authenticated SSH transport. Because the forwarding runs on its own thread, control returns to your program immediately and the tunnel operates while the rest of the application does other work — which is why a separate CloseTunnel is needed to shut it down cleanly.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the SshTunnel.BeginAccepting method, which creates and starts the local listener
-- on the given port.  The only argument is the listen port.  Connect and authenticate first;
-- clients accepted before authentication cannot be forwarded.

local tunnel = chilkat.SshTunnel.new()

tunnel.dest_hostname = "db.internal.example.com"
tunnel.dest_port = 5432

local sshPort = 22
local success = tunnel:connect("ssh.example.com", sshPort)
if not success then
    print(tunnel.last_error_text)
    return
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.
local password = "mySshPassword"

success = tunnel:authenticate_pw("mySshLogin", password)
if not success then
    print(tunnel.last_error_text)
    return
end

-- Start the local listener.  Local TCP connections to this port are forwarded to DestHostname:DestPort
-- through the SSH server.
local listenPort = 1080
success = tunnel:begin_accepting(listenPort)
if not success then
    print(tunnel.last_error_text)
    return
end

-- IsAccepting reports whether the listener thread is running.
if tunnel.is_accepting then
    print("The tunnel is accepting connections on port " .. listenPort)
end

-- ... the tunnel forwards traffic on a background thread while your application runs ...

local waitForThreadExit = true
success = tunnel:close_tunnel(waitForThreadExit)
if not success then
    print(tunnel.last_error_text)
    return
end