如何使用Golang执行带有给定sudo密码的shell命令

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

how to use Golang to shell command with given sudo password

问题

我可以帮你翻译这段代码。以下是翻译好的内容:

我想使用一段命令行代码在Go中设置日期时间,但是下面的代码失败了:

datetime := "2021-06-17 18:20:41.8"
sudoPassword := "xxxxx"
app := "echo"
arg0 := sudoPassword
arg1 := "|sudo -S"
arg2 := "date"
arg3 := "-s"
arg4 := "\"" + datetime + "\""
cmd := exec.Command(app, arg0, arg1, arg2, arg3, arg4)

有没有一种正确的方法来做到这一点?像在Python中那样自动填充密码:

os.system('echo %s|sudo -S %s' % (sudoPassword, command))

希望这能帮到你!

英文:

I'd like to use a piece of command line to set datetime in Go,
but the following code failed

datetime := "2021-06-17 18:20:41.8"
sudoPassword := "xxxxx"
app := "echo"
arg0 := sudoPassword
arg1 := "|sudo -S"
arg2 := "date"
arg3 := "-s"
arg4 := "\"" + datetime + "\""
cmd := exec.Command(app, arg0, arg1, arg2, arg3, arg4)

Is there a correct way to do this? Fill the password automatically like in Python

os.system('echo %s|sudo -S %s' % (sudoPassword, command))

答案1

得分: 2

你的代码存在一个问题,就是exec.Command直接执行命令而没有包装shell,但你构建了一个shell管道。你可以手动指定一个stdin reader来与sudo一起使用。

cmd := exec.Command("sudo", "-S", "--", "cat", "/etc/shadow")
cmd.Stdin = strings.NewReader("mysecretpassword") // 将你的密码直接传递给sudo的stdin
英文:

One issue with your code is that exec.Command execs commands directly without a wrapping shell, but you have constructed a shell pipeline. You can manually specify a stdin reader for use with sudo, though.

	cmd := exec.Command("sudo", "-S", "--", "cat", "/etc/shadow")
	cmd.Stdin = strings.NewReader("mysecretpassword") // your password fed directly to sudo's stdin

huangapple
  • 本文由 发表于 2021年7月5日 17:20:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/68253600.html
匿名

发表评论

匿名网友

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

确定