/
shell.go
94 lines (89 loc) · 2.1 KB
/
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
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
package shelli
import (
"io"
"golang.org/x/crypto/ssh"
)
// Stream the io.Reader to a channel, passing any errors on the given error channel.
func streamToChan(stream io.Reader, ch chan<- []byte, errCh chan<- error) {
for {
buf := make([]byte, 1<<10)
n, err := stream.Read(buf)
if n > 0 {
ch <- buf[0:n]
}
if err != nil {
errCh <- err
}
}
}
// Get stdin, stdout, and stderr from the SSH session.
func sessionStreams(session *ssh.Session) (stdin io.WriteCloser, stdout io.Reader, stderr io.Reader, err error) {
stdin, err = session.StdinPipe()
if err != nil {
return
}
stdout, err = session.StdoutPipe()
if err != nil {
return
}
stderr, err = session.StderrPipe()
if err != nil {
return
}
return
}
// NewPty creates a new SSH session to the client using inCh as stdin, and quiting on a receive to quit.
// Returns stdout, stderr channels and error channel
func NewPty(client *ssh.Client, inCh <-chan []byte, quit <-chan struct{}) (<-chan []byte, <-chan []byte, <-chan error) {
errCh := make(chan error, 1)
// Create a new session from the given configuration func.
session, err := client.NewSession()
if err != nil {
errCh <- err
return nil, nil, nil
}
// Get session std in/out/err
stdin, stdout, stderr, err := sessionStreams(session)
if err != nil {
errCh <- err
return nil, nil, nil
}
// Stream from readers to channels
stdoutCh := make(chan []byte)
stderrCh := make(chan []byte)
go streamToChan(stdout, stdoutCh, errCh)
go streamToChan(stderr, stderrCh, errCh)
// Set terminal modes
modes := ssh.TerminalModes{
ssh.VREPRINT: 0,
ssh.CS8: 1,
ssh.ECHOE: 1,
ssh.ECHOCTL: 0,
}
// Request pseudo terminal
err = session.RequestPty("xterm", 24, 80, modes)
//err = session.RequestPty("vt100", 24, 80, modes)
if err != nil {
errCh <- err
return nil, nil, nil
}
// Invoke SSH shell
err = session.Shell()
if err != nil {
errCh <- err
return nil, nil, nil
}
// Listen for input/quit
go func() {
for {
select {
case b := <-inCh:
stdin.Write(b)
case <-quit:
session.Close()
return
}
}
}()
return stdoutCh, stderrCh, errCh
}