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
package proxy
import (
"io"
"regexp"
"strings"
"sync"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/utils"
)
var ps1Pattern = regexp.MustCompile(`^\[?.*@.*\]?[\\$#]\s|mysql>\s`)
func NewCmdParser(sid, name string) *CmdParser {
parser := CmdParser{id: sid, name: name}
parser.initial()
return &parser
}
type CmdParser struct {
id string
name string
term *utils.Terminal
reader io.ReadCloser
writer io.WriteCloser
currentLines []string
lock *sync.Mutex
maxLength int
currentLength int
closed chan struct{}
}
func (cp *CmdParser) WriteData(p []byte) (int, error) {
select {
case <-cp.closed:
return 0, io.EOF
default:
}
return cp.writer.Write(p)
}
func (cp *CmdParser) Write(p []byte) (int, error) {
select {
case <-cp.closed:
return 0, io.EOF
default:
}
return len(p), nil
}
func (cp *CmdParser) Read(p []byte) (int, error) {
select {
case <-cp.closed:
return 0, io.EOF
default:
}
return cp.reader.Read(p)
}
func (cp *CmdParser) Close() error {
select {
case <-cp.closed:
return nil
default:
close(cp.closed)
}
_ = cp.reader.Close()
return cp.writer.Close()
}
func (cp *CmdParser) initial() {
cp.reader, cp.writer = io.Pipe()
cp.currentLines = make([]string, 0)
cp.lock = new(sync.Mutex)
cp.maxLength = 1024
cp.currentLength = 0
cp.closed = make(chan struct{})
cp.term = utils.NewTerminal(cp, "")
cp.term.SetEcho(false)
go func() {
logger.Infof("Session %s: %s start", cp.id, cp.name)
defer logger.Infof("Session %s: %s close", cp.id, cp.name)
loop:
for {
line, err := cp.term.ReadLine()
if err != nil {
select {
case <-cp.closed:
break loop
default:
}
goto loop
}
cp.lock.Lock()
cp.currentLength += len(line)
cp.currentLines = append(cp.currentLines, line)
// if cp.currentLength < cp.maxLength {
// cp.currentLines = append(cp.currentLines, line)
// }
cp.lock.Unlock()
}
}()
}
func (cp *CmdParser) parsePS1(s string) string {
return ps1Pattern.ReplaceAllString(s, "")
}
// Parse 解析命令或输出
func (cp *CmdParser) Parse() string {
select {
case <-cp.closed:
default:
cp.writer.Write([]byte("\r"))
}
cp.lock.Lock()
defer cp.lock.Unlock()
output := strings.TrimSpace(strings.Join(cp.currentLines, "\r\n"))
output = cp.parsePS1(output)
cp.currentLines = make([]string, 0)
cp.currentLength = 0
return output
}