/
ssh.go
122 lines (101 loc) · 2.47 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
package sshexec
import (
"github.com/satori/go.uuid"
"golang.org/x/crypto/ssh"
)
//
// Main agent struct
//
type SSHExecAgent struct {
results chan *ExecResult
AllReturn []ExecResult
listeners []func(*ExecResult)
running bool
}
// constructor
func NewAgent() *SSHExecAgent {
agent := &SSHExecAgent{
results: make(chan *ExecResult, 100),
running: false,
}
agent.Start()
return agent
}
//
// Runs a command with specified credentials (username/password)
//
func (agent *SSHExecAgent) RunWithCreds(username string, password string, authMethod []ssh.AuthMethod, hostname string, port int, command string) *uuid.UUID {
session := &HostSession{
Username: username,
Password: password,
Hostname: hostname,
Port: port,
Auths: authMethod,
}
return agent.RunWithSession(session, command)
}
func (agent *SSHExecAgent) TransferWithCreds(username string, password string, authMethod []ssh.AuthMethod, hostname string, port int, localFilePath string, remoteFilePath string) *uuid.UUID {
session := &HostSession{
Username: username,
Password: password,
Hostname: hostname,
Port: port,
Auths: authMethod,
}
return agent.TransferWithSession(session, localFilePath, remoteFilePath)
}
//
// Runs a command with a specified session
//
func (agent *SSHExecAgent) RunWithSession(session *HostSession, command string) *uuid.UUID {
id := uuid.NewV4()
go func(uuid uuid.UUID) {
r := session.Exec(uuid, command, session.GenerateConfig())
agent.results <- r
}(id)
return &id
}
//
// Runs a command with a specified session
//
func (agent *SSHExecAgent) TransferWithSession(session *HostSession, localFilePath string, remoteFilePath string) *uuid.UUID {
id := uuid.NewV4()
go func(uuid uuid.UUID) {
r := session.Transfer(uuid, localFilePath, remoteFilePath, session.GenerateConfig())
agent.results <- r
}(id)
return &id
}
//
// Add an ExecResult listener
//
func (agent *SSHExecAgent) AddListener(f func(*ExecResult)) {
agent.listeners = append(agent.listeners, f)
}
//
// Start the agent result channel and publish results as they come in to the channel
//
func (agent *SSHExecAgent) Start() {
if agent.running {
return
}
agent.running = true
go func() {
for agent.running {
select {
case result := <-agent.results:
if len(agent.listeners) > 0 {
for _, listener := range agent.listeners {
listener(result)
}
}
}
}
}()
}
//
// Stop the agent results channel
//
func (agent *SSHExecAgent) Stop() {
agent.running = false
}