/
ssh.go
89 lines (76 loc) · 1.63 KB
/
ssh.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package common
import (
"golang.org/x/crypto/ssh"
"os"
)
type SSH struct {
Addr string
User string
}
func (s *SSH) ExecuteWithPasswd(passwd, cmd string) ([]byte, error) {
// ssh config
config := &ssh.ClientConfig{
User: s.User,
Auth: []ssh.AuthMethod{
ssh.Password(passwd),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// connection ssh
conn, err := ssh.Dial("tcp", s.Addr, config)
if err != nil {
return nil, err
}
defer conn.Close()
// execute command
session, err := conn.NewSession()
if err != nil {
return nil, err
}
defer session.Close()
output, err := session.CombinedOutput(cmd)
if err != nil {
return nil, err
}
return output, nil
}
func (s *SSH) ExecuteWithKeyFile(file, cmd string) ([]byte, error) {
// SSH connection configuration
config := &ssh.ClientConfig{
User: s.User,
Auth: []ssh.AuthMethod{
publicKeyFile(file),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // HostKey authentication is ignored
}
// establish an SSH connection
client, err := ssh.Dial("tcp", s.Addr, config)
if err != nil {
return nil, err
}
// create a new SSH session
session, err := client.NewSession()
if err != nil {
return nil, err
}
defer session.Close()
// execute the command and get the output
output, err := session.Output(cmd)
if err != nil {
return nil, err
}
// return result
return output, nil
}
// publicKeyFile Use SSH key files for authentication
func publicKeyFile(file string) ssh.AuthMethod {
buffer, err := os.ReadFile(file)
if err != nil {
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil
}
return ssh.PublicKeys(key)
}