/
pw.go
73 lines (61 loc) · 1.09 KB
/
pw.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
package main
import (
"io/ioutil"
"os"
"strconv"
"strings"
)
type passwdEntry struct {
name string
passwd string
uid int
gid int
gecos string
dir string
shell string
}
func parsePasswd() ([]passwdEntry, error) {
passwdBytes, err := ioutil.ReadFile("/etc/passwd")
if err != nil {
return nil, err
}
passwdLines := strings.Split(string(passwdBytes), "\n")
var entries []passwdEntry
for _, line := range passwdLines {
parts := strings.Split(line, ":")
if len(parts) != 7 {
continue
}
uid, err := strconv.Atoi(parts[2])
if err != nil {
return nil, err
}
gid, err := strconv.Atoi(parts[3])
if err != nil {
return nil, err
}
entry := passwdEntry{
name: parts[0],
passwd: parts[1],
uid: uid,
gid: gid,
gecos: parts[4],
dir: parts[5],
shell: parts[6],
}
entries = append(entries, entry)
}
return entries, nil
}
func getPwNam(name string) *passwdEntry {
entries, err := parsePasswd()
if err != nil {
os.Exit(-1)
}
for _, entry := range entries {
if entry.name == name {
return &entry
}
}
return nil
}