1

I want to add an user to my server with golang exec function but its not working I tried multiple things but cant find an working solution. Is it maybe because of this? "$(openssl passwd -1 Test)"

here is my code

    cmd := exec.Command("sudo", "useradd -p", "$(openssl passwd -1 Test)", "Test1234")
    b, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%s\n", b)
Yariya
  • 87
  • 2
  • 8

1 Answers1

1

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.

Cameron Little
  • 3,487
  • 23
  • 35
  • Hello, its returning useradd: invalid field '$1$Gu9wY7nT$.Tl39zCwvI3.I1bV0rg.b1 ' – Yariya Mar 29 '21 at 13:20
  • That's going to be an issue with your usage of `useradd`. Make sure whatever you're trying to run through go works on the terminal as well. It looks like you need to encrypt the password with `crypt` first, using the `-p` option - https://linux.die.net/man/8/useradd. – Cameron Little Mar 29 '21 at 13:24
  • But why does it work on the terminal and not in go? When I put ```useradd -p $1$eHZrL9Px$RgxlN19Wu1S/yV8auzDeE/ Test``` It works – Yariya Mar 29 '21 at 13:31
  • I don't know. Are the `$` characters being expanded by your shell? (does it behave the same if you wrap the password string in single quotes?) – Cameron Little Mar 29 '21 at 13:33
  • I got the solution. ```a := strings.TrimSpace(string(password))``` and it worked – Yariya Mar 29 '21 at 13:39
  • Good idea, there might have been a trailing newline – Cameron Little Mar 29 '21 at 13:40