Skip to content

Instantly share code, notes, and snippets.

@jmsdnns
Last active June 9, 2023 13:33
Show Gist options
  • Save jmsdnns/1f1d23d3e5579ef3b454 to your computer and use it in GitHub Desktop.
Save jmsdnns/1f1d23d3e5579ef3b454 to your computer and use it in GitHub Desktop.
SSH to Vagrant instance with Golang
package main
import (
"bytes"
"fmt"
"golang.org/x/crypto/ssh"
"io/ioutil"
"log"
"os"
"time"
)
func loadPrivateKey() (ssh.Signer, error) {
pemBytes, err := ioutil.ReadFile(os.Getenv("HOME") + "/.vagrant.d/insecure_private_key")
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(pemBytes)
if err != nil {
return nil, err
}
return signer, nil
}
func executeCmd(cmd string, hostname string, config *ssh.ClientConfig) string {
conn, err := ssh.Dial("tcp", hostname, config)
if err != nil {
log.Fatalf("dial failed:%v", err)
}
defer conn.Close()
session, err := conn.NewSession()
if err != nil {
log.Fatalf("session failed:%v", err)
}
defer session.Close()
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Run(cmd)
return hostname + ": " + stdoutBuf.String()
}
func main() {
hosts := []string{"localhost:2222", "localhost:2222"}
signer, err := loadPrivateKey()
if err != nil {
log.Fatal(err)
}
config := &ssh.ClientConfig{
User: "vagrant",
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
}
results := make(chan string, 10)
timeout := time.After(5 * time.Second)
for _, hostname := range hosts {
go func(hostname string) {
results <- executeCmd("ls -l /projects", hostname, config)
}(hostname)
}
for i := 0; i < len(hosts); i++ {
select {
case res := <-results:
fmt.Print(res)
case <-timeout:
fmt.Println("Timed out!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment