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

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

您的代码的一个问题是 exec.Command 直接执行命令而没有包装 shell,但您构建了一个 shell 管道。不过,您可以手动指定标准输入 reader 以与 sudo 一起使用。

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