Skip to content

Instantly share code, notes, and snippets.

@dgjustice
Created February 28, 2023 00:44
Show Gist options
  • Save dgjustice/f8aff16853dc7a631b454356ab63d506 to your computer and use it in GitHub Desktop.
Save dgjustice/f8aff16853dc7a631b454356ab63d506 to your computer and use it in GitHub Desktop.
Connect to Arista device with crypto/ssh in Go.
import (
"bytes"
"fmt"
"log"
"net"
"os"
"golang.org/x/crypto/ssh"
)
func main() {
conn, err := net.Dial("tcp", "somehost:port")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
interactiveAuth := ssh.KeyboardInteractive(
func(user, instruction string, questions []string, echos []bool) ([]string, error) {
answers := make([]string, len(questions))
for i := range answers {
answers[i] = os.Getenv("SSHPASSWORD")
}
return answers, nil
},
)
config := &ssh.ClientConfig{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
User:os.Getenv("USER"),
Auth: []ssh.AuthMethod{interactiveAuth},
}
sshConn, chans, reqs, err := ssh.NewClientConn(conn, "somehost:port", config)
if err != nil {
log.Fatal(err)
}
client := ssh.NewClient(sshConn, chans, reqs)
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer session.Close()
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("show version"); err != nil {
log.Fatal("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
@dgjustice
Copy link
Author

@twr14152 thank you so much for taking the time to leave a comment! I am thrilled that you found this useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment