英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论