-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathremote_shell.go
64 lines (55 loc) · 1.34 KB
/
remote_shell.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
package main
import (
"context"
"github.com/melbahja/goph"
"golang.org/x/crypto/ssh"
"time"
)
// RemoteShell wraps a melbahja/goph SSH client and implements our Shell interface
type RemoteShell struct {
conn *goph.Client
opts RemoteShellOptions
}
type RemoteShellOptions struct {
Host string
Port uint
User string
Password string
KeyFile string
KeyPassword string
}
// Creates an SSH client using melbahja/goph library.
func NewRemoteShell(opts RemoteShellOptions) (*RemoteShell, error) {
var err error
var auth goph.Auth
shell := RemoteShell{opts: opts}
if len(opts.KeyFile) > 0 {
auth, err = goph.Key(opts.KeyFile, opts.KeyPassword)
if err != nil {
return nil, err
}
} else {
auth = goph.Password(opts.Password)
}
shell.conn, err = goph.NewConn(&goph.Config{
Auth: auth,
User: opts.User,
Addr: opts.Host,
Port: opts.Port,
Timeout: time.Second * 2,
Callback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
return nil, err
}
return &shell, nil
}
// Execute executes a command over SSH.
// `Goph` library provides exactly the function we need, so we just wrap it here.
func (r *RemoteShell) Execute(ctx context.Context, cmd string) ([]byte, error) {
sshCmd, err := r.conn.CommandContext(ctx, cmd)
if err != nil {
return nil, err
}
return sshCmd.CombinedOutput()
}