To ssh into a server we will use the crypto/ssh package and run commands on the remote machine. Please go through the comments in the code to better understand what each line of code is doing
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"golang.org/x/crypto/ssh"
)
func main() {
//There are different type of authentication method for SSh,
//username/password and publickey based auth.
// In this example you will see the publickey based authentication where password auth is setup with the remote server before hand.
//Below ling reads the ssh key to use for the authenticaion using ioutill readfile method
key, err := ioutil.ReadFile("/Users/mymachine/.ssh/id_rsa")
if err != nil {
log.Fatalf("unable to read private key: %v", err)
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Fatalf("unable to parse private key: %v", err)
}
config := &ssh.ClientConfig{
//user for the ssh
User: "ubuntu",
Auth: []ssh.AuthMethod{
// Use the PublicKeys method for remote authentication.
ssh.PublicKeys(signer),
},
//INSECURE use of HostKeyCallback below. if you would like to allow any host for ssh for the certverfication.
// here is actually comment from godoc
//https://godoc.org/golang.org/x/crypto/ssh#HostKeyCallback
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// Connect to the remote server and perform the SSH handshake.
sshClient, err := ssh.Dial("tcp", "192.168.64.2:22", config)
if err != nil {
log.Fatalf("unable to connect: %v", err)
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session. Create a new session to run a new command
session, err := sshClient.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("hostname"); err != nil {
log.Fatal("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}