-
-
Notifications
You must be signed in to change notification settings - Fork 235
/
xtmp.go
78 lines (70 loc) · 1.83 KB
/
xtmp.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
package agent
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
// CleanAllByKeyword delete any entries containing keyword in ALL known log files
func CleanAllByKeyword(keyword string) (err error) {
return deleteXtmpEntry(keyword)
}
// deleteXtmpEntry delete a wtmp/utmp/btmp entry containing keyword
func deleteXtmpEntry(keyword string) (err error) {
delete := func(path string) (err error) {
var (
offset = 0
newFileData []byte
)
xtmpf, err := os.Open(path)
if err != nil {
return fmt.Errorf("Failed to open xtmp: %v", err)
}
defer xtmpf.Close()
xmtpData, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("Failed to read xtmp: %v", err)
}
// back up xtmp file
err = ioutil.WriteFile(path+".bak", xmtpData, 0664)
if err != nil {
return fmt.Errorf("Failed to backup %s: %v", path, err)
}
for offset < len(xmtpData) {
buf := xmtpData[offset:(offset + 384)]
if strings.Contains(string(buf), keyword) {
offset += 384
continue
}
newFileData = append(newFileData, buf...)
offset += 384
}
// save new file as xtmp.tmp, users need to rename it manually, in case the file is corrupted
newXtmp, err := os.OpenFile(path+".tmp", os.O_CREATE|os.O_RDWR, 0664)
if err != nil {
return fmt.Errorf("Failed to open temp xtmp: %v", err)
}
defer newXtmp.Close()
err = os.Rename(path+".tmp", path)
if err != nil {
return fmt.Errorf("Failed to replace %s: %v", path, err)
}
_, err = newXtmp.Write(newFileData)
return err
}
err = nil
xtmpFiles := []string{"/var/log/wtmp", "/var/log/btmp", "/var/log/utmp"}
for _, xtmp := range xtmpFiles {
if IsFileExist(xtmp) {
e := delete(xtmp)
if e != nil {
if err != nil {
err = fmt.Errorf("DeleteXtmpEntry: %v, %v", err, e)
} else {
err = fmt.Errorf("DeleteXtmpEntry: %v", e)
}
}
}
}
return err
}