英文:
Running external commands through os/exec under another user
问题
使用os/exec
包,我想在*nix操作系统上代表另一个用户运行外部命令(当然,go进程在具有su特权的另一个用户的root用户下运行)。
我想避免使用"su"或"bash"命令,只使用go来实现。
我尝试使用syscall.Setuid
方法,但这会将用户更改为主项目的用户,我只需要将用户更改为外部子进程的用户:
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)
}
}
英文:
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)
}
}
答案1
得分: 41
你可以将syscall.Credential结构体添加到Cmd.SysProcAttr中。
cmd := exec.Command(command, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
英文:
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}
答案2
得分: 4
如果有人正在寻找一个可用的代码片段:
u, erru := user.Lookup(LocalUserName)
if erru != nil {
fmt.Println(erru, " for ", LocalUserName)
}
uid, err = strconv.ParseInt(u.Uid, 10, 32)
gid, err = strconv.ParseInt(u.Gid, 10, 32)
cmd := exec.Command("/bin/uname", "-a")
cmd.Stdout = &out
cmd.Stderr = &stderr
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}
err = cmd.Run()
希望这对你有帮助!
英文:
In case if someone is looking for a working code snippet:
u, erru := user.Lookup(LocalUserName)
if erru != nil {
fmt.Println( erru, " for ",LocalUserName)
}
uid, err = strconv.ParseInt(u.Uid, 10, 32)
gid, err = strconv.ParseInt(u.Gid, 10, 32)
cmd := exec.Command("/bin/uname", "-a")
cmd.Stdout = &out
cmd.Stderr = &stderr
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}
err = cmd.Run()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论