-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathssh_conn.go
49 lines (44 loc) · 1.01 KB
/
ssh_conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"io/ioutil"
"log"
"golang.org/x/crypto/ssh"
)
// PublicKeyFile returns an AuthMethod with your public key
func PublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
log.Println(err)
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
log.Println(err)
return nil
}
return ssh.PublicKeys(key)
}
func main() {
// copy ip and paste below
// don't forget to set your ssh key in the machine
sshConfig := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
PublicKeyFile("id_rsa"),
},
}
connection, err := ssh.Dial("tcp", "paste here the ip:22", sshConfig)
if err != nil {
log.Fatalf("Failed to dial: %s", err)
}
session, err := connection.NewSession()
if err != nil {
log.Fatalf("Failed to create session: %s", err)
}
// to change the command that will be runned, only modify CombinedOutput
output, err := session.CombinedOutput("ls -la")
if err != nil {
log.Fatal(err)
}
println(string(output))
}