Created
February 28, 2023 00:44
-
-
Save dgjustice/f8aff16853dc7a631b454356ab63d506 to your computer and use it in GitHub Desktop.
Connect to Arista device with crypto/ssh in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
Hey just wanted to say thank you for sharing your code. I struggled with keyboard interactive auth. Your example really helped. Thanks again.
@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
Setting up the socket manually isn't necessary. Here is a simpler version: