通过os/exec在另一个用户下运行外部命令

huangapple go评论88阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2014年2月11日 23:25:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/21705950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定