How to Create An SSH Tunnel in Go

Photo by Taylor Vick on Unsplash

Sometimes resources (such as database servers) are not publicly accessible. This is critical for security, but it can be a pain when writing scripts that need to access these resources for debugging and other ad-hoc tasks.

One solution is to create an SSH tunnel in bash and point your script to it. However:

  1. You may need to write scripts that are too complicated for bash.
  2. It can make your scripts brittle if you need to run multiple tunnels or forget to clean them up for long running processes.
  3. You may not have access to a separate terminal to run the SSH tunnel such as under some automation script.
  4. Want to use all your existing Go code, but bolt on the tunnel.
  5. Dislike bash.

Well, here you go. The following code supports creating multiple hassle-free SSH tunnels in pure Go and support using a private key or password authentication:

package main

Here is an example of usage:

func main() {
// Setup the tunnel, but do not yet start it yet.
tunnel := NewSSHTunnel(
// User and host of tunnel server, it will default to port 22
// if not specified.
"ec2-user@jumpbox.us-east-1.mydomain.com",

A big thanks to Svetlin Ralchev who provided a lot of the original bits and pieces.

If you prefer, the code is also available as a package at github.com/elliotchance/sshtunnel .

Originally published at http://elliot.land on January 15, 2019.

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store