v0.0.0-...-e560ebb Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2021 License: BSD-3-Clause Imports: 8 Imported by: 0



Package sshtunnel helps create a SSH tunnels between clients.




This section is empty.


This section is empty.


This section is empty.


type Tunnel

type Tunnel struct {
	// contains filtered or unexported fields

Tunnel to create SSH port forwarding between hosts.

func NewTunnel

func NewTunnel(localAddr string, remoteAddr string, c *ssh.Client) (*Tunnel, error)

NewTunnel sets up SSH port forwarding so that commands sent to the remote address (remoteAddr) on client "c" are forwarded to the local address (localAddr).

It returns a new Tunnel that can be closed after use.

const (
	remoteAddr     = ""
	remoteHostAddr = "remoteHostname:22"
// In this example, we set up an HTTP server on the local machine and
// expose it to a remote device via ssh tunnel, so on the remote device,
// we can access the http service on "localhost:<OS assigned port>".
s := http.Server{}
http.HandleFunc("/foo", func(w http.ResponseWriter, _ *http.Request) {
	fmt.Fprint(w, "Hello World!\n")
// Use port "0" to request the OS to assign an unused port number.
ln, err := net.Listen("tcp", ":0")
if err != nil {
	panic(fmt.Sprintf("Error starting the listener: %s", err))
defer ln.Close()
go s.Serve(ln)
defer s.Shutdown(context.Background())
// Get the listener's address.
localAddr := ln.Addr().String()
// Create the SSH client.
client, err := ssh.Dial("tcp", remoteHostAddr, &ssh.ClientConfig{})
if err != nil {
	panic(fmt.Sprintf("Error connecting to %s: %s", client.RemoteAddr().String(), err))
defer client.Close()
// Create the SSH tunnel.
t, err := NewTunnel(localAddr, remoteAddr, client)
if err != nil {
	panic(fmt.Sprintf("Error setting up SSH tunnel: %s", err))
defer t.Close()
// Get address of the listener on the client.
lnAddr := t.RemoteAddr().String()
// Send commands over the created tunnel.
cs, err := client.NewSession()
if err != nil {
	panic(fmt.Sprintf("Error staring new session on %s: %s", remoteHostAddr, err))
defer cs.Close()
err = cs.Run(fmt.Sprintf("curl %s/foo", lnAddr))
if err != nil {
	panic(fmt.Sprintf("Error running 'curl %s/foo' on %s: %s", lnAddr, remoteHostAddr, err))

func (*Tunnel) Close

func (t *Tunnel) Close()

Close closes the tunnel including all resources, and ongoing connections.

func (*Tunnel) IsAlive

func (t *Tunnel) IsAlive() bool

IsAlive checks if the Tunnel is alive. If the tunnel is in the process of shutting down but not fully shut down, this method will return false.

func (*Tunnel) RemoteAddr

func (t *Tunnel) RemoteAddr() net.Addr

RemoteAddr returns the address and port on which the service is running on the remote device.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL