3

I've written a go function to execute commands using bash inside docker container from ubuntu 20.04.

func commandExecution(command string) (error, string, string) {
    var output bytes.Buffer
    var error bytes.Buffer

    cmd := exec.Command("bash", "-c", command)
    cmd.Stdout = &output
    cmd.Stderr = &error
    err := cmd.Run()

    return err, output.String(), error.String()
}

when I try to execute some commands like below

err, _, _ := commandExecution("sudo mkdir -p " + directory)

or

err, _, _ := commandExecution("sudo cp " + source + " " + destination)

I'm just getting the

error exit status 127

I tried executing again directly

 docker exec container bash -c mv --help

mv: missing file operand

Help me out!

Vrangle
  • 323
  • 5
  • 13
  • make sure you're providing two operands e.g source & destination. Most probably you're providing one. – Jibon Dec 20 '21 at 09:52
  • err, _, _ := commandExecution("sudo cp " + source + " " + destination) I verified. also when I try to execute err, _, _ := commandExecution("sudo systemctl start someservice") I'm getting the same exit status 127 – Vrangle Dec 20 '21 at 09:56
  • 1
    Depending on your setup the issue might be with trying to run a command with `sudo`, not the actual code. Try running something that does not require root priveleges. Also this might be relevant https://stackoverflow.com/questions/25845538/how-to-use-sudo-inside-a-docker-container – Szymig Dec 20 '21 at 11:24
  • Your examples have a major security issue: what happens if `directory` contains punctuation, like `directory := "foo; sudo rm -rf /"`? Can you use an array of single-word arguments and avoid the `bash -c` wrapper? – David Maze Dec 20 '21 at 11:47
  • (Does a shell script, or maybe even a Dockerfile, fit your needs better than a Go program?) – David Maze Dec 20 '21 at 11:47
  • As @Szymig pointed out, ubuntu 20.04 image's builtin shell does not have sudo, systemctl. I manually installed while deploying. – Vrangle Dec 20 '21 at 12:46

0 Answers0