-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathssh.go
More file actions
189 lines (165 loc) · 3.88 KB
/
ssh.go
File metadata and controls
189 lines (165 loc) · 3.88 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package ssh
import (
"fmt"
"strings"
"time"
gossh "golang.org/x/crypto/ssh"
)
type ConnInfo struct {
User string `json:"user"`
Addr string `json:"addr"`
Port int `json:"port"`
AuthMode string `json:"authMode"`
Password string `json:"password"`
PrivateKey []byte `json:"privateKey"`
PassPhrase []byte `json:"passPhrase"`
DialTimeOut time.Duration `json:"dialTimeOut"`
}
type SSHClient struct {
Client *gossh.Client `json:"client"`
}
func NewClient(c ConnInfo) (*SSHClient, error) {
if strings.Contains(c.Addr, ":") {
c.Addr = fmt.Sprintf("[%s]", c.Addr)
}
config := &gossh.ClientConfig{}
config.SetDefaults()
addr := fmt.Sprintf("%s:%d", c.Addr, c.Port)
config.User = c.User
if c.AuthMode == "password" {
config.Auth = []gossh.AuthMethod{gossh.Password(c.Password)}
} else {
signer, err := makePrivateKeySigner(c.PrivateKey, c.PassPhrase)
if err != nil {
return nil, err
}
config.Auth = []gossh.AuthMethod{gossh.PublicKeys(signer)}
}
if c.DialTimeOut == 0 {
c.DialTimeOut = 5 * time.Second
}
config.Timeout = c.DialTimeOut
config.HostKeyCallback = gossh.InsecureIgnoreHostKey()
proto := "tcp"
if strings.Contains(c.Addr, ":") {
proto = "tcp6"
}
client, err := gossh.Dial(proto, addr, config)
if nil != err {
return nil, err
}
return &SSHClient{Client: client}, nil
}
func (c *SSHClient) Run(shell string) (string, error) {
session, err := c.Client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
buf, err := session.CombinedOutput(shell)
return string(buf), err
}
func (c *SSHClient) SudoHandleCmd() string {
if _, err := c.Run("sudo -n ls"); err == nil {
return "sudo "
}
return ""
}
func (c *SSHClient) Runf(shell string, args ...interface{}) (string, error) {
session, err := c.Client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
buf, err := session.CombinedOutput(fmt.Sprintf(shell, args...))
return string(buf), err
}
func (c *SSHClient) Close() {
_ = c.Client.Close()
}
func makePrivateKeySigner(privateKey []byte, passPhrase []byte) (gossh.Signer, error) {
if len(passPhrase) != 0 {
return gossh.ParsePrivateKeyWithPassphrase(privateKey, passPhrase)
}
return gossh.ParsePrivateKey(privateKey)
}
func (c *SSHClient) RunWithStreamOutput(command string, outputCallback func(string)) error {
session, err := c.Client.NewSession()
if err != nil {
return fmt.Errorf("failed to create SSH session: %w", err)
}
defer session.Close()
stdout, err := session.StdoutPipe()
if err != nil {
return fmt.Errorf("failed to set up stdout pipe: %w", err)
}
stderr, err := session.StderrPipe()
if err != nil {
return fmt.Errorf("failed to set up stderr pipe: %w", err)
}
if err := session.Start(command); err != nil {
return fmt.Errorf("failed to start command: %w", err)
}
stdoutCh := make(chan string, 100)
stderrCh := make(chan string, 100)
doneCh := make(chan struct{})
go func() {
buffer := make([]byte, 1024)
for {
n, err := stdout.Read(buffer)
if err != nil {
close(stdoutCh)
return
}
if n > 0 {
stdoutCh <- string(buffer[:n])
}
}
}()
go func() {
buffer := make([]byte, 1024)
for {
n, err := stderr.Read(buffer)
if err != nil {
close(stderrCh)
return
}
if n > 0 {
stderrCh <- string(buffer[:n])
}
}
}()
go func() {
for {
select {
case stdoutOutput, ok := <-stdoutCh:
if !ok {
stdoutCh = nil
if stderrCh == nil {
close(doneCh)
return
}
continue
}
if outputCallback != nil {
outputCallback(stdoutOutput)
}
case stderrOutput, ok := <-stderrCh:
if !ok {
stderrCh = nil
if stdoutCh == nil {
close(doneCh)
return
}
continue
}
if outputCallback != nil {
outputCallback(stderrOutput)
}
}
}
}()
err = session.Wait()
<-doneCh
return err
}