Files
processes/linux_setuser.go
2022-09-05 11:42:31 +08:00

52 lines
982 B
Go

//go:build !windows && !darwin
// +build !windows,!darwin
package processes
import (
"os/user"
"strconv"
"strings"
"syscall"
)
// 设置进程的运行用户
func (that *ProcessPlus) SetUser() error {
userName := that.User
if len(userName) == 0 {
return nil
}
//check if group is provided
pos := strings.Index(userName, ":")
groupName := ""
if pos != -1 {
groupName = userName[pos+1:]
userName = userName[0:pos]
}
u, err := user.Lookup(userName)
if err != nil {
return err
}
uid, err := strconv.ParseUint(u.Uid, 10, 32)
if err != nil {
return err
}
gid, err := strconv.ParseUint(u.Gid, 10, 32)
if err != nil && groupName == "" {
return err
}
if groupName != "" {
g, err := user.LookupGroup(groupName)
if err != nil {
return err
}
gid, err = strconv.ParseUint(g.Gid, 10, 32)
if err != nil {
return err
}
}
that.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid), NoSetGroups: true}
return nil
}