How to Create An SSH Tunnel in Go

Elliot Chance
Jan 15, 2019 · 4 min read
Image for post
Image for post
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:

Here is an example of usage:

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.

Elliot Chance

Written by

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

Elliot Chance

Written by

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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