/
client.go
283 lines (233 loc) · 6.29 KB
/
client.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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package ssh
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/juanfont/gitlab-machine/pkg/utils"
"github.com/moby/term"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
const (
ErrCreatingNativeGoClient = utils.Error("Error creating native Go SSH client")
)
type Auth struct {
Passwords []string
Keys []string
}
type Client interface {
Output(command string) (string, error)
OutputWithPty(command string) (string, error)
Shell(args ...string) error
// Start starts the specified command without waiting for it to finish. You
// have to call the Wait function for that.
//
// The first two io.ReadCloser are the standard output and the standard
// error of the executing command respectively. The returned error follows
// the same logic as in the exec.Cmd.Start function.
Start(command string) (io.ReadCloser, io.ReadCloser, error)
// Wait waits for the command started by the Start function to exit. The
// returned error follows the same logic as in the exec.Cmd.Wait function.
Wait() error
}
type NativeClient struct {
Config ssh.ClientConfig
Hostname string
Port int
openSession *ssh.Session
openClient *ssh.Client
}
func NewClient(user string, host string, port int, auth *Auth) (Client, error) {
log.Debug().Msgf("Creating SSH client for %s@%s:%d", user, host, port)
return NewNativeClient(user, host, port, auth)
}
func NewNativeClient(user, host string, port int, auth *Auth) (Client, error) {
config, err := NewNativeConfig(user, auth)
if err != nil {
log.Error().Err(err).Msg("Error creating SSH client config")
return nil, ErrCreatingNativeGoClient
}
return &NativeClient{
Config: config,
Hostname: host,
Port: port,
}, nil
}
func NewNativeConfig(user string, auth *Auth) (ssh.ClientConfig, error) {
var (
authMethods []ssh.AuthMethod
)
for _, k := range auth.Keys {
key, err := ioutil.ReadFile(k)
if err != nil {
return ssh.ClientConfig{}, err
}
privateKey, err := ssh.ParsePrivateKey(key)
if err != nil {
return ssh.ClientConfig{}, err
}
authMethods = append(authMethods, ssh.PublicKeys(privateKey))
}
for _, p := range auth.Passwords {
authMethods = append(authMethods, ssh.Password(p))
}
return ssh.ClientConfig{
User: user,
Auth: authMethods,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}, nil
}
func (client *NativeClient) Wait() error {
err := client.openSession.Wait()
if err != nil {
return err
}
_ = client.openSession.Close()
err = client.openClient.Close()
if err != nil {
return err
}
client.openSession = nil
client.openClient = nil
return nil
}
func (client *NativeClient) Shell(args ...string) error {
var (
termWidth, termHeight int
)
conn, err := ssh.Dial("tcp", net.JoinHostPort(client.Hostname, strconv.Itoa(client.Port)), &client.Config)
if err != nil {
return err
}
defer closeConn(conn)
session, err := conn.NewSession()
if err != nil {
return err
}
defer session.Close()
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Stdin = os.Stdin
modes := ssh.TerminalModes{
ssh.ECHO: 1,
}
fd := os.Stdin.Fd()
if term.IsTerminal(fd) {
oldState, err := term.MakeRaw(fd)
if err != nil {
return err
}
defer term.RestoreTerminal(fd, oldState)
winsize, err := term.GetWinsize(fd)
if err != nil {
termWidth = 80
termHeight = 24
} else {
termWidth = int(winsize.Width)
termHeight = int(winsize.Height)
}
}
if err := session.RequestPty("xterm", termHeight, termWidth, modes); err != nil {
return err
}
if len(args) == 0 {
if err := session.Shell(); err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
} else {
if err := session.Run(strings.Join(args, " ")); err != nil {
return err
}
}
return nil
}
func (client *NativeClient) Start(command string) (io.ReadCloser, io.ReadCloser, error) {
conn, session, err := client.session(command)
if err != nil {
return nil, nil, err
}
stdout, err := session.StdoutPipe()
if err != nil {
return nil, nil, err
}
stderr, err := session.StderrPipe()
if err != nil {
return nil, nil, err
}
if err := session.Start(command); err != nil {
return nil, nil, err
}
client.openClient = conn
client.openSession = session
return ioutil.NopCloser(stdout), ioutil.NopCloser(stderr), nil
}
func (client *NativeClient) Output(command string) (string, error) {
conn, session, err := client.session(command)
if err != nil {
return "", nil
}
defer closeConn(conn)
defer session.Close()
output, err := session.CombinedOutput(command)
return string(output), err
}
func (client *NativeClient) OutputWithPty(command string) (string, error) {
conn, session, err := client.session(command)
if err != nil {
return "", nil
}
defer closeConn(conn)
defer session.Close()
fd := int(os.Stdout.Fd())
termWidth, termHeight, err := terminal.GetSize(fd)
if err != nil {
return "", err
}
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
// request tty -- fixes error with hosts that use
// "Defaults requiretty" in /etc/sudoers - I'm looking at you RedHat
if err := session.RequestPty("xterm", termHeight, termWidth, modes); err != nil {
return "", err
}
output, err := session.CombinedOutput(command)
return string(output), err
}
func (client *NativeClient) dialSuccess() bool {
conn, err := ssh.Dial("tcp", net.JoinHostPort(client.Hostname, strconv.Itoa(client.Port)), &client.Config)
if err != nil {
log.Debug().Err(err).Msg("Error dialing TCP")
return false
}
closeConn(conn)
return true
}
func (client *NativeClient) session(command string) (*ssh.Client, *ssh.Session, error) {
if err := mcnutils.WaitFor(client.dialSuccess); err != nil {
return nil, nil, fmt.Errorf("error attempting SSH client dial: %s", err)
}
conn, err := ssh.Dial("tcp", net.JoinHostPort(client.Hostname, strconv.Itoa(client.Port)), &client.Config)
if err != nil {
return nil, nil, fmt.Errorf("mysterious error dialing TCP for SSH (we already succeeded at least once) : %s", err)
}
session, err := conn.NewSession()
return conn, session, err
}
func closeConn(c io.Closer) {
err := c.Close()
if err != nil {
log.Debug().Err(err).Msg("Error closing SSH client")
}
}