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