Using Go to establish SSH connections to network devices and execute CLI commands. Introduction to SSH libraries like golang.org/x/crypto/ssh.
Write a Go program that connects to the SR Linux node (from Day 6's Containerlab setup) via SSH, executes show system information, and prints the output.
// main.go
// main.go
package main
import (
"fmt"
"log"
"time"
"golang.org/x/crypto/ssh"
)
func main() {
// SSH client config
config := &ssh.ClientConfig{
User: "admin",
Auth: []ssh.AuthMethod{
ssh.Password("NokiaSrl1!"), // Default password for SR Linux
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // NOT for production!
Timeout: 5 * time.Second,
}
// Connect to the SSH server (replace with your SR Linux management IP/hostname)
// For Containerlab, typically the node name resolves to its IP in the docker network
conn, err := ssh.Dial("tcp", "clab-srl-single-srl1:22", config)
if err != nil {
log.Fatalf("Failed to dial: %v", err)
}
defer conn.Close()
// Create a new session
session, err := conn.NewSession()
if err != nil {
log.Fatalf("Failed to create session: %v", err)
}
defer session.Close()
// Run the command
output, err := session.CombinedOutput("show system network-instance")
if err != nil {
log.Fatalf("Failed to run command: %v", err)
}
fmt.Println(string(output))
}- Ensure your
srl_single.clab.yamlfrom Day 6 is deployed. - Run
go mod init day7. - Run
go get golang.org/x/crypto/ssh. - Save the code as
main.go. - Run
go run main.go.