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