forked from msteinert/pam
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasswd.go
More file actions
97 lines (82 loc) · 2.09 KB
/
passwd.go
File metadata and controls
97 lines (82 loc) · 2.09 KB
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
package pam
//#include <sys/types.h>
//#include <stdlib.h>
//#include <pwd.h>
//extern struct passwd *getpwent (void);
//extern void endpwent (void);
//#cgo CFLAGS: -Wall -std=c99 -ansi
//#cgo LDFLAGS: -lpam
import "C"
import (
"fmt"
"os/exec"
"strings"
"unsafe"
)
type UserInfo struct {
Username string /* username */
UserId uint /* user ID */
GroupId uint /* group ID */
UserInformation string /* user information */
HomeDirectory string /* home directory */
ShellProgram string /* shell program */
}
func GetUserInfos(userId string) (*UserInfo, error) {
user := C.CString(userId)
defer C.free(unsafe.Pointer(user))
pwnam, err := C.getpwnam(user)
if err != nil {
return nil, err
}
if pwnam == nil {
return nil, fmt.Errorf("unable to reach user info")
}
return passwdToUserInfo(pwnam), nil
}
func ChangeUserName(userId string, userName string) error {
cmd := exec.Command("chfn", userId, "-f", userName)
return execCommand(cmd)
}
func ChangeUserEmail(userId string, email string) error {
cmd := exec.Command("chfn", userId, "-o", email)
return execCommand(cmd)
}
func AddGroup(username string, group string) error {
cmd := exec.Command("usermod", "-aG", group, username)
return execCommand(cmd)
}
func RemoveGroup(username string, group string) error {
cmd := exec.Command("gpasswd", "-d", username, group)
return execCommand(cmd)
}
func ChangeGroups(username string, groups []string) error {
args := []string{
"-G",
}
args = append(args, strings.Join(groups, ","))
args = append(args, username)
cmd := exec.Command("usermod", args...)
return execCommand(cmd)
}
func ListUsers() ([]UserInfo, error) {
var users []UserInfo
defer C.endpwent()
for {
pwnam := C.getpwent()
if pwnam == nil {
return users, nil
}
users = append(users, *passwdToUserInfo(pwnam))
}
}
func passwdToUserInfo(passwd *C.struct_passwd) *UserInfo {
infos := UserInfo{
C.GoString(passwd.pw_name),
uint(C.uint(passwd.pw_uid)),
uint(C.uint(passwd.pw_gid)),
C.GoString(passwd.pw_gecos),
C.GoString(passwd.pw_dir),
C.GoString(passwd.pw_shell),
}
return &infos
}