-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshclient.go
204 lines (176 loc) · 4.07 KB
/
sshclient.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
package main
import (
"bufio"
"golang.org/x/crypto/ssh"
sshagent "golang.org/x/crypto/ssh/agent"
"io"
"log"
"net"
"os"
"strings"
)
func getSshAgent() (agent sshagent.Agent, err error) {
conn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
return
}
agent = sshagent.NewClient(conn)
return
}
func sshDial(hostname string, username string) (conn *ssh.Client, err error) {
agent, err := getSshAgent()
if err != nil {
return nil, err
}
auths := []ssh.AuthMethod{
ssh.PublicKeysCallback(agent.Signers),
}
conn, err = ssh.Dial("tcp", hostname,
&ssh.ClientConfig{
User: username,
Auth: auths,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
return
}
func sshRunOutput(conn *ssh.Client, cmd string) (output string, err error) {
session, err := conn.NewSession()
if err != nil {
return
}
defer session.Close()
b, err := session.Output(cmd)
if err != nil {
return
}
return string(b), nil
}
func sshRunOutLogger(conn *ssh.Client, cmd string, logger *log.Logger, stdinChannel chan []byte) (term chan bool, loggerReturn chan error, err error) {
session, err := conn.NewSession()
if err != nil {
return
}
if StdinIsTerminal() {
/* We have to request a pty so that our command exits when the session
* closes. Ideally we'd send a TERM signal for the Session using
* session.Signal(ssh.SIGTERM), but OpenSSH doesn't support that yet:
* https://bugzilla.mindrot.org/show_bug.cgi?id=1424
*/
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
terminal := os.Getenv("TERM")
if terminal == "" {
terminal = "xterm"
}
err = session.RequestPty(terminal, 80, 40, modes)
if err != nil {
return
}
} else {
logger.Println("[WARNING] pty not requested because stdin is not a terminal")
}
var stdinPipe io.WriteCloser
if stdinChannel != nil {
stdinPipe, err = session.StdinPipe()
if err != nil {
return
}
}
stdoutPipe, err := session.StdoutPipe()
if err != nil {
return
}
stdout := channelFromReader(stdoutPipe)
stderrPipe, err := session.StderrPipe()
if err != nil {
return
}
stderr := channelFromReader(stderrPipe)
err = session.Start(cmd)
if err != nil {
return
}
term = make(chan bool, 1)
loggerReturn = make(chan error, 1)
go func() {
var err error // shadow outer err
shouldTerm := <-term
if shouldTerm {
// We can't use this, as OpenSSH doesn't support it. See above.
/* err = session.Signal(ssh.SIGTERM)
* if err != nil {
* logger.Println("remote terminantion error: " + err.Error())
* } */
// We have to just close the session instead.
err = session.Close()
if err != nil {
logger.Println("session close error: " + err.Error())
}
}
}()
go func() {
defer session.Close()
for {
select {
case inBytes, ok := <-stdinChannel:
if ok {
stdinPipe.Write(inBytes)
} else {
stdinPipe.Close()
stdinChannel = nil
}
case line, ok := <-stdout:
if ok {
logger.Println(line)
} else {
stdout = nil
}
case line, ok := <-stderr:
if ok {
logger.Println(line)
} else {
stderr = nil
}
}
if stdinChannel == nil && stdout == nil && stderr == nil {
break
}
}
err := session.Wait()
close(term)
if exitError, ok := err.(*ssh.ExitError); ok && exitError.Signal() == "HUP" {
err = nil
}
loggerReturn <- err
}()
return
}
func cleanOutputLine(line string) (out []string) {
line = strings.TrimSpace(line)
line = strings.Replace(line, "\r", "\n", -1)
line = strings.Replace(line, "\n\n", "\n", -1)
return strings.Split(line, "\n")
}
func channelFromReader(pipe io.Reader) (ch chan string) {
ch = make(chan string)
go func() {
reader := bufio.NewReader(pipe)
for {
in, err := reader.ReadString('\n')
if (err == io.EOF && in != "") || err == nil {
lines := cleanOutputLine(in)
for _, line := range lines {
ch <- line
}
}
if err != nil {
close(ch)
return
}
}
}()
return
}