SSH Recipes in Go — Part One

Vagmi Mudumbai
Nov 28, 2018 · 2 min read

Go has an amazing standard library and it has a pure-go implementation of SSH. This means that you can use Go to interact with remote SSH servers. Why would you want to do that? Well, you can automate many tasks on your server by triggering things on the remote machine and do some cool SSH tunneling.

Establishing a connection

SSH is implemented by the golang.org/x/crypto/ssh package. Before you can dial into an SSH server you need to setup the ClientConfig. A sample SSH client config looks a bit like this.

The AuthMethod interface implements the actual auth() method and the method() method which returns one of the valid RFC 4252 method names. So for instance, if we have to use the public key based authentication, you would have to do something like this.

We can now use this client config to ssh into our machine. I have also setup the InsecureIgnoreHostKey() method. I was running vagrant so I used it to accept connections to my local VM. I would recommend that you read the docs before making your choice or writing your own.

Thats it. This performs the authentication, key exchange. Now to do anything useful with this SSH connection, we need to create a session. Once a session is created, you can execute a single command over the session.

You can now use the runCommand method to run an executable on the server with the SSH connection. You can create any number of sessions on an existing client but you can only run one command per session. So with just a few lines of code, we can establish a connection and run remote commands using Go. Next in the series, we’ll attempt to do the following. So, follow me to stay tuned.

  • Setup an SSH server with Go
  • Tunnel connections with SSH and Go
  • Understand how SCP works and reimplement SCP in Go

Tarka Labs Blog

Tarka Labs is a team of passionate hackers, designers and product managers. We believe in experimental methods to identify the best solutions to problems instead of working on technology du jour. Visit us at https://tarkalabs.com/

Vagmi Mudumbai

Written by

Building an awesome team @tarkalabs. Hacks on golang, kubernetes and vim.

Tarka Labs Blog

Tarka Labs is a team of passionate hackers, designers and product managers. We believe in experimental methods to identify the best solutions to problems instead of working on technology du jour. Visit us at https://tarkalabs.com/