Golang SSH Client: Multiple Commands, Crypto & Goexpect Examples

Golang SSH client examples

golang ssh clientBuilding a Go SSH client is common when automating network systems. The golang.org/x/crypto/ssh package is the official SSH package  supported by the Go team. It works with SSH version 2 and is compatible with OpenSSH and other SSH spec servers.

Client setup may differ depending on whether you issue a single command, multiple commands, or need an interactive session.


Single Command Example

Here’s a simple example that runs a single command on a remote host using the Golang crypto SSH library. You’ll notice the HostKeyCallback to setup a FixedHostKey references the target host public key; this is used to prevent spoofing. If your host public key isn’t already archived in the your home directory OpenSSH known_hosts file, you can run ssh-keyscan to pull it off the target host.

Multiple Command Example

Here’s an example that uses a username and password to authenticate and then runs through multiple commands. It will send the output to stdout as it is. Uncomment the three relevant sections if you prefer to store the output in a variable.

Golang SSH Client Supported Ciphers

The Golang SSH Client specifies the default preference for ciphers (see preferredCiphers list):

The Golang SSH Client lists supported ciphers that are not recommend(see supportedCiphers list):

  • aes128-ctr
  • aes192-ctr
  • aes256-ctr
  • [email protected]
  • chacha20Poly1305ID
  • arcfour256
  • arcfour128
  • arcfour
  • aes128cbcID
  • tripledescbcID

Take note in cipherModes :

  • CBC mode is insecure and so is not included in the default config.(See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely needed, it’s possible to specify a custom Config to enable it. You should expect that an active attacker can recover plaintext if you do.
  • 3des-cbc is insecure and is not included in the default config.

A custom Config example to additionally allow cbc may look like this below:

Likewise you could explicitly list your custom ciphers in ClientConfig:

Golang Expect Example

The goexpect library is convenient and easy to use. Be aware that due to the goterm package, it cannot be compiled on Windows. Here’s a simple example using a couple commands. Be sure to include your target host, user and pass if you try the example below.

See also:
Golang DNS Lookup
Golang IP Address Manipulation
Golang Regular Expression Match