以另一个用户身份执行

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

Exec as another user

问题

如何在GO中使用另一个用户执行shell命令并获取输出?

我尝试了以下代码:

cmd := exec.Command("sudo", "su", username, "-c", command)
stdout, err := cmd.StdoutPipe()
CheckErr(err)
cmd.Run()

但是没有输出。有人知道如何解决这个问题吗?

英文:

How to execute shell command with another user in GO, and get output from it ?

I tried:

cmd :=exec.Command("sudo","su",username, "-c",command)
stdout, err := cmd.StdoutPipe()
CheckErr(err)
cmd.Run()

there is no output. anyone know how to do this?

答案1

得分: 1

你需要检查运行cmd.Run的输出,并且使用stdout获取输出比使用管道更简单。

cmd := exec.Command("sudo", "su", username, "-c", command)
cmd.Stderr = os.Stdout
cmd.Stdout = os.Stdout

err := cmd.Run()
CheckErr(err)

这样可以让你看到错误信息,以便找出导致sudo失败的原因。

英文:

You need to check the output of running the cmd.Run and also get your output using stdout is simpler than using the pipe.

cmd :=exec.Command("sudo","su",username, "-c",command)
cmd.Stderr = os.Stdout
cmd.Stdout = os.Stdout

err := cmd.Run()
CheckErr(err)

That should give you visibility of the error so you can find out what is occuring that prevents the sudo.

huangapple
  • 本文由 发表于 2014年5月9日 09:03:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/23555095.html
匿名

发表评论

匿名网友

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

确定