exec.Command
runs an executable directly. Each string is a literal argument. In your example, sudo
is the program, and you're passing useradd -p
as the first argument, then $(openssl passwd -1 Test)
as the second, etc.
useradd -p
is it's own command, and won't work as a single string argument.
$(openssl passwd -1 Test)
is bash (or another shell) specific syntax, which won't work in exec.Command
.
You're actually trying to run three executables - sudo
, useradd
, and openssl
. You can either run each executable in a separate exec.Command
call or run a shell directly.
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)
(I'd recommend not running sudo
directly in your go code, as the program you're running should be managing permissions directly.)
To run a shell directly to use the $(...)
subcommand syntax, see https://stackoverflow.com/a/24095983/2178159.