How do I execute a command on a remote machine in a golang CLI? I need to write a golang CLI that can SSH into a remote machine via a key and execute a shell command. Furthermore, I need to be able to do this one hop away. e.g. SSH into a machine (like a cloud bastion) and then SSH into another, internal, machine and execute a shell command.
I haven't (yet) found any examples for this.
You can run commands on a remote machine over SSH using the
"golang.org/x/crypto/ssh"
package.Here is an example function demonstrating simple usage of running a single command on a remote machine and returning the output:
Try the package https://github.com/appleboy/easyssh-proxy
See more example.
The other solutions here will work, but I'll throw out another option you could try: simplessh. I think it is easier to use. For this question, I would use option 3 below where you can ssh using your key.
Option 1: SSH to a machine with a password, then run a command
Option 2: SSH to a machine using a set of possible passwords, then run a command
Option 3: SSH to a machine using your key
Try with os/exec https://golang.org/pkg/os/exec/ to execute a ssh
To jump over machines use the ProxyCommand directive in a ssh config file.