/
executor.go
98 lines (81 loc) · 1.87 KB
/
executor.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
package main
import (
"errors"
"os"
"strings"
"time"
"github.com/appleboy/easyssh-proxy"
)
const PORT_SSH_DEFAULT = 22
var (
ErrHostUsername error = errors.New("error: Hostname or user can not be empty.")
)
type ErrConnect struct {
hostname string
reason error
}
func (this *ErrConnect) Error() string {
return "error: Can't connect to host " + this.hostname + ", reason: " + this.reason.Error()
}
type Result struct {
Message string
Error error
}
type SSHExecutor struct {
Hostname string
Port int
User string
Password string
Commands []string
Session *easyssh.MakeConfig
}
func (this *SSHExecutor) SetCommands(commands []string) {
this.Commands = commands
}
func (this *SSHExecutor) Exec() *Result {
result := &Result{}
err := this.connect()
if err != nil {
result.Error = err
return result
}
commands := strings.Join(this.Commands, ";")
stdout, stderr, _, err1 := this.Session.Run(commands)
if err1 != nil || stderr != "" {
result.Error = errors.New(stderr)
} else if stdout != "" {
result.Message = stdout
}
this.disconnect()
return result
}
func (this *SSHExecutor) connect() error {
homeDir, _ := os.UserHomeDir()
this.Session = &easyssh.MakeConfig{
User: this.User,
Server: this.Hostname,
Password: this.Password,
KeyPath: homeDir + "/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
return nil
}
func (this *SSHExecutor) disconnect() error {
if this.Session != nil {
this.Session = nil
}
return nil
}
func NewExecutor(hostname, user, password string, port int) (*SSHExecutor, error) {
if hostname == "" || user == "" {
return nil, ErrHostUsername
}
exec := &SSHExecutor{Hostname: hostname, Port: port, User: user, Password: password}
testErr := exec.connect()
defer exec.disconnect()
if testErr != nil {
return nil, &ErrConnect{hostname: hostname, reason: testErr}
}
return exec, nil
}