Using the os/exec
package, I want to run an external command on a *nix OS, on behalf of another user (of course go process run under root user of another user with su privileges)
I want avoid "su" or "bash" commands and make it purely with go.
I made an approach using syscall.Setuid
but this will change the user to the main project, I just need change the user to the external child process:
func (self *Command) LoseTo(username string) {
u, err := user.Lookup(username)
if err != nil {
fmt.Printf("%v", err)
}
uid, err := strconv.Atoi(u.Uid)
if err := syscall.Setuid(uid); err != nil {
fmt.Printf("%v", err)
}
}
You can add a syscall.Credential struct to Cmd.SysProcAttr
cmd := exec.Command(command, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}