Last active
May 17, 2024 23:16
-
-
Save ilmanzo/9cf5ed25ea3bb5ba7e588ffb95ab1940 to your computer and use it in GitHub Desktop.
example for ssh client in Go with username and password authentication
This file contains 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
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