Zig
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
const socket = try chilkat.Socket.init();
defer socket.deinit();
// Connect to the SSH server and initialize an SSH tunneling session. Port 22 is conventional but
// not required.
socket.sshOpenTunnel("ssh.example.com", 22) catch {
std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
return;
};
// Authenticate the SSH session before opening forwarded channels.
// The SSH password should come from a secure source rather than being hard-coded.
const ssh_password = "mySshPassword";
socket.sshAuthenticatePw("sshUser", ssh_password) catch {
std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
return;
};
// 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.
const b_tls = false;
const max_wait_ms = 20000;
const channel = try chilkat.Socket.init();
defer channel.deinit();
socket.sshNewChannel("db.internal", 5432, b_tls, max_wait_ms, channel) catch {
std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
return;
};
// Use the channel socket to send and receive with the destination through the tunnel.
std.debug.print("Forwarded channel opened to the destination.\n", .{});
}