-
Notifications
You must be signed in to change notification settings - Fork 0
/
passwd.go
122 lines (98 loc) · 1.94 KB
/
passwd.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
package hosts
import (
"strings"
"github.com/go-zoox/core-utils/cast"
"github.com/go-zoox/errors"
"github.com/go-zoox/fs"
)
type Passwd struct {
FilePath string
Mapping map[string]*PasswdItem
}
func New(filepath string) *Passwd {
return &Passwd{
FilePath: filepath,
Mapping: make(map[string]*PasswdItem),
}
}
func (p *Passwd) Load() error {
lines, err := fs.ReadFileLines(p.FilePath)
if err != nil {
return err
}
for _, line := range lines {
if strings.HasPrefix(line, "#") {
continue
}
if strings.TrimSpace(line) == "" {
continue
}
item, err := parsePasswdItem(line)
if err != nil {
return err
}
p.Mapping[item.User] = item
}
return nil
}
func (p *Passwd) Get(user string) (*PasswdItem, error) {
if item, ok := p.Mapping[user]; ok {
return item, nil
}
return nil, errors.Errorf("not found: %s", user)
}
func (p *Passwd) GetUID(user string) (int, error) {
item, err := p.Get(user)
if err != nil {
return 0, err
}
return item.UID, nil
}
func (p *Passwd) GetGID(user string) (int, error) {
item, err := p.Get(user)
if err != nil {
return 0, err
}
return item.GID, nil
}
func (p *Passwd) GetHome(user string) (string, error) {
item, err := p.Get(user)
if err != nil {
return "", err
}
return item.Home, nil
}
func (p *Passwd) GetShell(user string) (string, error) {
item, err := p.Get(user)
if err != nil {
return "", err
}
return item.Shell, nil
}
func (p *Passwd) Length() int {
return len(p.Mapping)
}
type PasswdItem struct {
User string
Pass string
UID int
GID int
Gecos string
Home string
Shell string
}
func parsePasswdItem(text string) (*PasswdItem, error) {
items := strings.Split(text, ":")
if len(items) != 7 {
return nil, errors.Errorf("invalid passwd item: %s", text)
}
return &PasswdItem{
User: items[0],
Pass: items[1],
UID: cast.ToInt(items[2]),
GID: cast.ToInt(items[3]),
Gecos: items[4],
Home: items[5],
Shell: items[6],
}, nil
}