Skip to content

Instantly share code, notes, and snippets.

@ilmanzo
Last active May 17, 2024 23:16
Show Gist options
  • Save ilmanzo/9cf5ed25ea3bb5ba7e588ffb95ab1940 to your computer and use it in GitHub Desktop.
Save ilmanzo/9cf5ed25ea3bb5ba7e588ffb95ab1940 to your computer and use it in GitHub Desktop.
example for ssh client in Go with username and password authentication
package main
import (
"bytes"
"fmt"
"log"
"golang.org/x/crypto/ssh"
)
func main() {
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", "myserver:22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer session.Close()
// 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("/bin/hostname"); err != nil {
log.Fatal("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment