exec.Command 直接运行可执行文件。每个字符串都是一个文字参数。在您的示例中,sudo 是程序,您将 useradd -p 作为第一个参数传递,然后将 $(openssl passwd -1 Test) 作为第二个参数传递,等等。
useradd -p 是它自己的命令,不能作为单个字符串参数工作。
$(openssl passwd -1 Test) 是 bash(或其他 shell)特定语法,在 exec.Command 中不起作用。
您实际上是在尝试运行三个可执行文件 - sudo、useradd 和 openssl。您可以在单独的 exec.Command 调用中运行每个可执行文件,也可以直接运行 shell。
cmd := exec.Command("openssl", "passwd", "-1", "Test")
passwordBytes, err := cmd.CombinedOutput()
if err != nil {
panic(err)
}
// remove whitespace (possibly a trailing newline)
password := strings.TrimSpace(string(passwordBytes))
cmd = exec.Command("useradd", "-p", password, "Test1234")
b, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s\n", b)
(我建议不要直接在您的 go 代码中运行 sudo,因为您正在运行的程序应该直接管理权限。)
要直接运行 shell 以使用 $(...) 子命令语法,请参阅 https://stackoverflow.com/a/24095983/2178159。