-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathssh.go
269 lines (234 loc) · 5.25 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
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
package ssh
import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"path/filepath"
"strings"
"time"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// Clienter defines interface of SSH client
type Clienter interface {
WithServer(add string) Client
WithUser(user string) Client
WithPassword(password string) Client
WithKey(key string) Client
WithPort(port string) Client
Connectable(timeout time.Duration) (bool, error)
RunCommand(command string, options CommandOptions) error
}
// Client ssh client
type Client struct {
server string
port string
user string
key string
password string
session *ssh.Session
conn ssh.Conn
}
// New create a client
func New(server string) Client {
home, _ := homedir.Dir()
return Client{
server: server,
user: "root",
port: "22",
key: filepath.Join(home, ".ssh/id_rsa"),
}
}
// WithServer with server
func (c Client) WithServer(addr string) Client {
return Client{
server: addr,
port: c.port,
user: c.user,
key: c.key,
password: c.password,
}
}
// WithUser with key
func (c Client) WithUser(user string) Client {
return Client{
server: c.server,
port: c.port,
user: user,
key: c.key,
password: c.password,
}
}
// WithPassword with key
func (c Client) WithPassword(password string) Client {
return Client{
server: c.server,
port: c.port,
user: c.user,
key: c.key,
password: password,
}
}
// WithKey with key
func (c Client) WithKey(keyfile string) Client {
return Client{
server: c.server,
port: c.port,
user: c.user,
key: keyfile,
password: c.password,
}
}
// WithPort with port
func (c Client) WithPort(port string) Client {
return Client{
server: c.server,
port: port,
user: c.user,
key: c.key,
password: c.password,
}
}
// CommandOptions options for command
type CommandOptions struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
Timeout time.Duration
Env []string
}
// RunCommand run command onto remote server via SSH
func (c Client) RunCommand(command string, options CommandOptions) error {
timeout := 20 * time.Second
if options.Timeout > 0 {
timeout = options.Timeout
}
client, err := c.connect(timeout)
if err != nil {
return err
}
defer func() {
if err := client.disconnect(); err != nil {
fmt.Println("-->", err)
log.Println(err)
}
}()
if options.Stdin != nil {
stdin, err := client.session.StdinPipe()
if err != nil {
return fmt.Errorf("Unable to setup stdin for session: %v", err)
}
// nolint
go io.Copy(stdin, options.Stdin)
}
if options.Stdout != nil {
stdout, err := client.session.StdoutPipe()
if err != nil {
return fmt.Errorf("Unable to setup stdout for session: %v", err)
}
// nolint
go io.Copy(options.Stdout, stdout)
}
if options.Stderr != nil {
stderr, err := client.session.StderrPipe()
if err != nil {
return fmt.Errorf("Unable to setup stderr for session: %v", err)
}
// nolint
go io.Copy(options.Stderr, stderr)
}
for _, env := range options.Env {
variable := strings.Split(env, "=")
if len(variable) != 2 {
continue
}
if err := client.session.Setenv(variable[0], variable[1]); err != nil {
return err
}
}
return client.session.Run(command)
}
// Connectable check if client can connect to ssh server within timeout
func (c Client) Connectable(timeout time.Duration) (bool, error) {
client, err := c.connect(timeout)
if err != nil {
return false, err
}
defer func() {
if err := client.disconnect(); err != nil {
fmt.Println("-->", err)
log.Println(err)
}
}()
return true, nil
}
// Connect connect server
func (c Client) connect(timeout time.Duration) (Client, error) {
Auth := []ssh.AuthMethod{}
if c.password != "" {
Auth = append(Auth, ssh.Password(c.password))
} else if c.key != "" {
publicKey, err := publicKey(c.key)
if err != nil {
return Client{}, err
}
Auth = append(Auth, publicKey)
} else {
return Client{}, fmt.Errorf("password or keyfile required for ssh connection ")
}
config := &ssh.ClientConfig{
User: c.user,
Auth: Auth,
Timeout: timeout,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil },
}
addr := net.JoinHostPort(c.server, c.port)
conn, err := ssh.Dial("tcp", addr, config)
if err != nil {
return Client{}, err
}
session, err := conn.NewSession()
if err != nil {
return Client{}, err
}
return Client{
server: c.server,
port: c.port,
user: c.user,
key: c.key,
password: c.password,
conn: conn,
session: session,
}, nil
}
// Disconnect disconnect with server
func (c Client) disconnect() error {
if err := c.session.Close(); err != nil {
// "https://github.com/golang/go/issues/28108"
if err == io.EOF {
return nil
}
return errors.Wrap(err, "session close failure")
}
if err := c.conn.Close(); err != nil {
return errors.Wrap(err, "connection close failure")
}
return nil
}
func publicKey(file string) (ssh.AuthMethod, error) {
buffer, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil, err
}
return ssh.PublicKeys(key), nil
}
var (
_ Clienter = Client{}
)