/
connSsh.go
100 lines (87 loc) · 1.88 KB
/
connSsh.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
package srvconn
import (
"errors"
"io"
gossh "golang.org/x/crypto/ssh"
)
func NewSSHConnection(sess *gossh.Session, opts ...SSHOption) (*SSHConnection, error) {
if sess == nil {
return nil, errors.New("ssh session is nil")
}
options := &SSHOptions{
win: Windows{
Width: 80,
Height: 120,
},
term: "xterm",
}
for _, setter := range opts {
setter(options)
}
modes := gossh.TerminalModes{
gossh.ECHO: 1, // enable echoing
gossh.TTY_OP_ISPEED: 14400, // input speed = 14.4 kbaud
gossh.TTY_OP_OSPEED: 14400, // output speed = 14.4 kbaud
}
err := sess.RequestPty(options.term, options.win.Height, options.win.Width, modes)
if err != nil {
return nil, err
}
stdin, err := sess.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := sess.StdoutPipe()
if err != nil {
return nil, err
}
conn := &SSHConnection{
session: sess,
stdin: stdin,
stdout: stdout,
options: options,
}
err = sess.Shell()
if err != nil {
_ = sess.Close()
return nil, err
}
return conn, nil
}
type SSHConnection struct {
session *gossh.Session
stdin io.Writer
stdout io.Reader
options *SSHOptions
}
func (sc *SSHConnection) SetWinSize(w, h int) error {
return sc.session.WindowChange(h, w)
}
func (sc *SSHConnection) Read(p []byte) (n int, err error) {
return sc.stdout.Read(p)
}
func (sc *SSHConnection) Write(p []byte) (n int, err error) {
return sc.stdin.Write(p)
}
func (sc *SSHConnection) Close() (err error) {
return sc.session.Close()
}
func (sc *SSHConnection) KeepAlive() error {
_, err := sc.session.SendRequest("keepalive@openssh.com", false, nil)
return err
}
type SSHOption func(*SSHOptions)
type SSHOptions struct {
win Windows
term string
}
func SSHPtyWin(win Windows) SSHOption {
return func(opt *SSHOptions) {
opt.win = win
}
}
func SSHTerm(termType string) SSHOption {
return func(opt *SSHOptions) {
opt.term = termType
}
}