/
pshell_history.go
133 lines (108 loc) · 2.58 KB
/
pshell_history.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
// Copyright (c) 2022 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package ssh
import (
"bufio"
"fmt"
"io"
"os"
"os/user"
"strings"
"sync"
"time"
"github.com/blacknon/lssh/output"
)
type pShellHistory struct {
Timestamp string
Command string
Result string
Output *output.Output
}
//
func (ps *pShell) NewHistoryWriter(server string, output *output.Output, m *sync.Mutex) *io.PipeWriter {
// craete pShellHistory struct
psh := &pShellHistory{
Command: ps.latestCommand,
Timestamp: time.Now().Format("2006/01/02_15:04:05 "), // "yyyy/mm/dd_HH:MM:SS "
Output: output,
}
// create io.PipeReader, io.PipeWriter
r, w := io.Pipe()
// output Struct
go ps.pShellHistoryPrint(psh, server, r, m)
// return io.PipeWriter
return w
}
func (ps *pShell) pShellHistoryPrint(psh *pShellHistory, server string, r *io.PipeReader, m *sync.Mutex) {
count := ps.Count
var result string
sc := bufio.NewScanner(r)
loop:
for {
for sc.Scan() {
text := sc.Text()
result = result + text + "\n"
}
if sc.Err() == io.ErrClosedPipe {
break loop
}
select {
case <-time.After(50 * time.Millisecond):
continue
}
}
// Add Result
psh.Result = result
// Add History
m.Lock()
ps.History[count][server] = psh
m.Unlock()
}
// GetHistoryFromFile return []History from historyfile
func (ps *pShell) GetHistoryFromFile() (data []pShellHistory, err error) {
// user path
usr, _ := user.Current()
histfile := strings.Replace(ps.HistoryFile, "~", usr.HomeDir, 1)
// Open history file
file, err := os.OpenFile(histfile, os.O_RDONLY, 0600)
if err != nil {
return
}
defer file.Close()
sc := bufio.NewScanner(file)
for sc.Scan() {
line := sc.Text()
text := strings.SplitN(line, " ", 2)
if len(text) < 2 {
continue
}
d := pShellHistory{
Timestamp: text[0],
Command: text[1],
Result: "",
}
data = append(data, d)
}
return
}
// PutHistoryFile put history text to s.HistoryFile
// ex.) write history(history file format)
// YYYY-mm-dd_HH:MM:SS command...
// YYYY-mm-dd_HH:MM:SS command...
// ...
func (ps *pShell) PutHistoryFile(cmd string) (err error) {
// user path
usr, _ := user.Current()
histfile := strings.Replace(ps.HistoryFile, "~", usr.HomeDir, 1)
// Open history file
file, err := os.OpenFile(histfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return
}
defer file.Close()
// Get Time
timestamp := time.Now().Format("2006/01/02_15:04:05 ") // "yyyy/mm/dd_HH:MM:SS "
fmt.Fprintln(file, timestamp+cmd)
return
}